0

Basically when I click a button I want to call a function and run the button click function:

This jQuery runs when the page loads:

jQuery( document ).ready( function ( $ ) {
  $('ul li:first-child').addClass( 'first_item' );
  className = $('.first_item').attr('id');
  alert('Date is:'+ className +'.');
});

And this jQuery runs when the a button is clicked:

jQuery( document ).ready( function ( $ ) {
    $('.button').click(function() {
        $('.tweets ul').prepend($('.refreshMe').html());
    });
});

I want to do both when the button is clicked, how can i combine the two?

P.P:

What If i wanted to add another function into the mix, all to run together:

    $(".refreshMe").everyTime(5000,function(i){
        $.ajax({
          url: "test.php?latest="+className+"",
          cache: false,
          success: function(html){
            $(".refreshMe").html(html);
          }
        })
    })

2 Answers 2

2

Place the code that runs on page load in a function that is called in both situations.

    // Place all the code in one .ready() function instead of two.
jQuery( document ).ready( function ( $ ) {

       // Place your code in its own function
    function initialize() {
        $('ul li:first-child').addClass( 'first_item' );
        className = $('.first_item').attr('id');
        alert('Date is:'+ className +'.');
    }

       // Call the function on page load
    initialize();

    $('.button').click(function() {
        $('.tweets ul').prepend($('.refreshMe').html());
           // Call the function in the click handler
        initialize();
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use a separate function, like this:

function doThings() {
    $('ul li:first-child').addClass( 'first_item' );
    className = $('.first_item').attr('id');
    alert('Date is:'+ className +'.');
}

$(document).ready(function () {
    doThings();
    $('.button').click(function () {
        $('.tweets ul').prepend($('.refreshMe').html());
        doThings();
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.