orglce
orglce

Reputation: 543

Set CSS properties on load with jQuery

I have some elements on my website that need to be updated every time page is being scrolled or resized. So I made a small jQuery code to do that.

$(window).scroll(function(){
    setSlideshowButtons();
});

$(window).resize(function() { 
    setSlideshowButtons();
});

function setSlideshowButtons() {
    var size = $(".slides img").height(); 
    $(".navigation_buttons").css("margin-top", "-" + size/2 + "px");
}

And so far everything worked great. But than I found out that I also have to set those properties on document load. So I also put this in the document.ready function.

$(document).ready(function(){
    setSlideshowButtons();
});

But it doesn't seem to work. But when I scroll or resize the window, function runs itself and CSS properties change.

Upvotes: 0

Views: 99

Answers (3)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

$(document).ready(function(){
    var size;
    var setSlideshowButtons = function () {
      size = $(".slides img").height(); 
      $(".navigation_buttons").css("margin-top", "-" + size/2 + "px");
    }
    setSlideshowButtons();
    $(window).on('resize scroll', setSlideshowButtons);
});

Upvotes: 0

Daria
Daria

Reputation: 276

Looks like image still doesn't load, on document ready. Try to re-call function on image load.

var img = $(".slides img");
    img.onload = setSlideshowButtons;

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

If you are doing any manipulations like creating a Slide Show and manipulating them, then you need to execute the setSlideshowButtons() function after the plugin's initialization has been called.

Say, example:

$(document).ready(function () {
    $(".slider").slider({
      option: value,
      option: value
    });
    // Place it after the init.
    setSlideshowButtons();
});

Upvotes: 1

Related Questions