MR.Don't know MR.Don't know - 1 year ago 51
Javascript Question

jquery click element with same class

I got list of elements, when i click on first other 10 are also active,
how to target only one that is really active?
this is my js code

$(document).ready(function() {
$('.inspiration-row').on('click', function() {
$('inspiration-block').toggleClass('shift-left shift-right');
//$('.inspiration-block').toggleClass('span12 span8');
$('.inspiration-right').toggleClass('span0 span2');

Answer Source

I wrote a fiddle to demonstrate my solution (let me know if it does not do exactly what you intended).

$(function($) {
  $(document).on('click', '.inspiration-row', function(event) {
    var target = $('.inspiration-row');
    target.find('.inspiration-block').toggleClass('shift-left shift-right');
    //$('.inspiration-block').toggleClass('span12 span8');
    target.find('.inspiration-right').toggleClass('span0 span2');

This registers a ready callback that captures $ so if another script loads jquery, it won't affect us. It uses event delegation to capture all click events on the entire page that occur inside an element matching .inspiration-row.

The refers to the source of the event, the element that the event came from. I use .closest to search up from the one actually clicked to find the nearest ancestor that matches .inspiration-row.

From there, target refers to that whole .inspiration-row, we look for those two descendent selectors and toggle the appropriate classes.

You were toggling both class names, as though that would make it pick one or the other. That is only true if the element initially has one of those names. I added one of the class names to the first inspiration-row so the toggles will make it have one or the other, at any one time.