0

I have 4 bootstrap cards their ids are: card0 card1 card2 card3 and I have 4 label marks their ids are: mark0 mark1 mark2 mark3

I want to add 4 different events in each Card:

for (var i = 0; i < 4; i++) {
  var cardx = '#card' + i;
  var markx = '#mark' + i;

  $(cardx).hover(function (i) {
    $(markx).removeClass('map-icon map-icon-beauty-salon');
    $(markx).addClass('map-icon map-icon-postal-code-prefix');
  }, function (i) {
    $(markx).removeClass('map-icon map-icon-postal-code-prefix');
    $(markx).addClass('map-icon map-icon-beauty-salon');
  });
}

The code above only create the same event in the 4 cards

1
  • can you plz post your html and css code? Commented Aug 18, 2018 at 4:10

2 Answers 2

2

You need to use each loop in stand of for

Try this:

$(document).ready(function(){
    
    $('.cardHolder div').each(function (i) {
        var markx = '#mark' + i;
        $(this).hover(function() {
            $(markx).removeClass('map-icon map-icon-beauty-salon');
            $(markx).addClass('map-icon map-icon-postal-code-prefix');
        }, function () {
            $(markx).removeClass('map-icon map-icon-postal-code-prefix');
            $(markx).addClass('map-icon map-icon-beauty-salon');
        });
    })

});
label{display:block}
.map-icon-beauty-salon{
    color:#0094ff;
}
.map-icon-postal-code-prefix{
    color:#ff6a00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Hover mouse on Card : </p>
<div class="cardHolder">
    <div id="card0">Card 1</div>
    <div id="card1">Card 2</div>
    <div id="card2">Card 3</div>
    <div id="card3">Card 4</div>
</div>
<hr />

<label id="mark0">Mark 1</label>
<label id="mark1">Mark 2</label>
<label id="mark2">Mark 3</label>
<label id="mark3">Mark 4</label>

Sign up to request clarification or add additional context in comments.

1 Comment

This works for me. I made a little change $("div[id^='card']").each(function)
0

It will add hover events to each of #card[i] element. The problem is #mark[i] elements. Because of closure issue, it will always act on #mark3. You should attach i to the event and use that value.

$(cards).on('mouseenter', {i: i}, function (e) {
  var markx = '#mark' + e.data.i;
  $(markx).removeClass('map-icon map-icon-beauty-salon');
  $(markx).addClass('map-icon map-icon-postal-code-prefix');
}).on('mouseleave', {i: i}, function (e) {
  var markx = '#mark' + e.data.i;
  $(markx).removeClass('map-icon map-icon-postal-code-prefix');
  $(markx).addClass('map-icon map-icon-beauty-salon');
});

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.