Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple selectors on click function, how to know which selector was clicked?

new to Jquery here. I have four selectors on a click function, see code below, this is because I want the same effect happening on all of them when clicked, instead of making a click function for all four selectors. However, when clicked I want the function to identify which selector was clicked so I can perform an action on one of the selectors, this is why I use id's instead of a class. More precise, I want to set the CSS on a clicked selector to a higher z-index value so it will not be effected by the effect that will be taking place, in this case I want the clicked selector to have an z-index value of 10.

I tried using a if statement, see below, but it's not working, anyone know how to do this?

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

My jQuery attempt:

$(document).ready(function(e) {

var effect = $("#slide");

$("#1, #2, #3, #4").click(function() {

    effect.animate({width: "1100px"}, 200, "easeOutQuint");
    $("#2").data('clicked', true);

    if ($("#2").data('clicked')) {
       $("#2").css("z-index", "10");
    }

});
});
like image 576
Nils Karlsson Avatar asked Sep 21 '25 01:09

Nils Karlsson


2 Answers

Use this keyword:

$(document).ready(function(e) {

var effect = $("#slide");

$("#1, #2, #3, #4").click(function() {

    effect.animate({width: "1100px"}, 200, "easeOutQuint");
    $(this).data('clicked', true);

    if ($(this).data('clicked')) {
       $(this).css("z-index", "10");
    }

});
});
like image 143
StoYan Avatar answered Sep 22 '25 15:09

StoYan


You can simply use this within your click callback to determine the clicked element:

$("#1, #2, #3, #4").click(function() {
    effect.animate({width: "1100px"}, 200, "easeOutQuint");
    $(this).data('clicked', true);

    if ($(this).data('clicked')) {
        $(this).css("z-index", "10");
    }
});

However, in order to make it work, you don't need use IDs. It is a much better idea to use one common class instead of IDs if possible:

<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

And in JavaScript:

$(document).ready(function(e) {
    var effect = $("#slide");

    $(".myClass").click(function() {
        effect.animate({width: "1100px"}, 200, "easeOutQuint");
        $(this).data('clicked', true);

        if ($(this).data('clicked')) {
           $(this).css("z-index", "10");
        }
    });
});

Note that there is not much sense in your if ($(this).data('clicked')) condition. Since you set clicked to true right before condition, it will always be true.

like image 45
Yeldar Kurmangaliyev Avatar answered Sep 22 '25 14:09

Yeldar Kurmangaliyev