user3426703
user3426703

Reputation: 19

Jquery: Adding css class to certain divs based on attributes

I have several divs that all have the an attribute called number.

<div class="foo" number="1"></div>
<div class="foo" number="2"></div>
<div class="foo" number="3"></div>

...and so on.

When I click on one of them, I catch the number and store it in a variable. I then want to run a function that adds an extra class to f.eks: all the divs with the number-attribute between [the one I clicked] to +7.

Kind of like some datepickers do. How would I do this. I tried using each(), but failed.

Upvotes: 1

Views: 82

Answers (3)

David Pucko
David Pucko

Reputation: 81

Try this:

http://jsfiddle.net/dejvidpi/36th41k6/2/

It uses the same method you said - gets the clicked ID and then it goes through all the divs and marks selected + 7.

It's kinda wasteful, because it loops through all the divs, but it should point you in the right direction.

$(document).ready(function(){
    $('div').click(function(){
        $('div').removeClass("active");

        var id = parseInt($(this).attr("number"));

        $.each($('div'), function(index, item){
            var currId = parseInt($(item).attr("number"));
            if (currId >= id && currId <= id + 7)
                $(item).addClass("active");
        });
    });
});

edit: I had the post window opened all the time while working on fiddle, I see you already got some pretty similar answers.

Upvotes: 1

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

See this fiddle: http://jsfiddle.net/nd2e33dp/

you can write a function like this

$(function(){
    $('.foo').click(function(e){

        var num=parseInt($(this).attr('data-number'));


        $('.foo').each(function(i,ele){
             var compare=parseInt($(e.target).attr('data-number'))+7;
              var eleNumber=parseInt($(ele).attr('data-number'));
           if( eleNumber>=num && eleNumber<compare)
              {
                  console.log('in');
        $(ele).addClass('red');              
              }

        });


    });

})

Upvotes: 2

Eddi
Eddi

Reputation: 811

Quick & Dirty:

$(document).ready(function(){
$(".foo").click(function(){
 var low = parseInt($(this).attr("number"));
 var high = low + 7;  

    $(".foo").each(function(){
          var num = $(this).attr("number");
          if (num > low && num < high){
             //YourFunction   
          }
      });
});   
});

Upvotes: 1

Related Questions