Richard Šimek
Richard Šimek

Reputation: 77

Run one jQuery function on multiple elements with the same class

I have problem with running one jquery function on two or more elements. It runs properly on the first element in the HTML code, but doesn't work properly on others.

I have this jQuery:

$(window).load(function(){
$('.background_square_1 li.bg_square').hide();

function rotate() {
$(".background_square_1 li.bg_square").first().appendTo('.background_square_1').fadeOut(500);
$(".background_square_1 li.bg_square").first().fadeIn(500);

setTimeout(rotate, 10000);
}
rotate();
});

And HTML like this:

<ul class="background_square_1 gallery_background">
<li class="bg_square bg_1"></li>
<li class="bg_square bg_2"></li>
<li class="bg_square bg_3"></li>
<li class="bg_square bg_4"></li>
</ul>

<ul class="background_square_1 gallery_background">
<li class="bg_square bg_1"></li>
<li class="bg_square bg_2"></li>
<li class="bg_square bg_3"></li>
<li class="bg_square bg_4"></li>
</ul>

Basically, what I am trying to achiveve is to run the function on both (but can be more!) ul elements with background_square_1 class.

Truth be told, I do not work with javascript or jQuery, so please keep this in mind.

Here is Fiddle showing my problem: http://fiddle.jshell.net/bWHPg/

Upvotes: 0

Views: 3014

Answers (4)

user2587132
user2587132

Reputation:

http://fiddle.jshell.net/bWHPg/5/

setInterval(function() { 
  $('.background_square_1').find('li:first')
        .fadeOut(500)
        .next()
        .fadeIn(500)
         .next()
        .fadeIn(500)
        .end()
        .appendTo(".background_square_1");
},  500);

Upvotes: 0

maverickosama92
maverickosama92

Reputation: 2725

just remove .first() in your code your code would work fine

working fiddle here: http://fiddle.jshell.net/bWHPg/2/

Upvotes: 0

defau1t
defau1t

Reputation: 10619

Wrap your code inside document.ready rather than window.load

$(function() {
   //jQuery code here
});

Upvotes: 0

PaReeOhNos
PaReeOhNos

Reputation: 4428

Just target that class directly. So for example

$(".gallery_background").function()

Or, if the function can't be called like that and you want to process each element with something else you could do

$(".gallery_background").each(function(index, item){
    var elm = $(this);
    ... Do stuff ...
})

I could have got index and item the wrong way round but you get the idea :)

Upvotes: 1

Related Questions