Shniper
Shniper

Reputation: 854

Select the direct next of a certain element

I am trying to add a class to the next p element after the item that is clicked. In my function the part that removes the class is working but the selector for the p element is not correct so nothing is happening with that.

DEMO

function classChange() {
    if($(this).hasClass('active')) {
        //do nothing
    }
    else {
        $('.active').removeClass('active');
        $(this).next('p').addClass('active');
    }
}

$('h1').click(function() {
    classChange();
});

Upvotes: 1

Views: 59

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

In your classChange() function, this refers to the Window object (assuming the function is in the global scope).

If you want it to refer to the clicked H1 element, define the click event like this:

$('h1').click(classChange);

If you want to toggle the next P element's display, define classChange() like this:

function classChange() {
  $(this).next('p').toggleClass('active');
}

Fiddle 1

If, instead, you want to always show one of the P elements, define it like this:

function classChange() {
  $('.active').removeClass('active');
  $(this).next('p').addClass('active');
}

Fiddle 2

Upvotes: 4

JF-Mechs
JF-Mechs

Reputation: 1081

You're doing something wrong here..

One noticeable is

if($(this).hasClass('active')) {

$(this) returns window and not the selected element in which the event is binded to the h1.

Since you are invoking a function to do that, you can add a parameter to that function passing the $(this).

Here is the demo..

function classChange(e) {
		//$(this)
    //would return window and not the h1
    if($(e).next('p').hasClass('active')) {
        //do nothing
    }
    else {
        $('.active').removeClass('active');
        $(e).next('p').addClass('active');
    }
}

$('h1').click(function() {
	classChange($(this));
});
p {
  opacity: 0;
}

.active {
  opacity: 1 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Hello
</h1>
<p class="active">
  hello
</p>
<h1>
Goodbye
</h1>
<p>
  Goodbye
</p>

Upvotes: 0

Tan Li Hau
Tan Li Hau

Reputation: 2334

The this in classChange is not what you think it is. You can try do the below to bind the e.target as this in the classChange() function:

function classChange() {
    if($(this).hasClass('active')) {
        //do nothing
    }
    else {
        $('.active').removeClass('active');
        $(this).next('p').addClass('active');
    }
}

$('h1').click(function(e) {
    classChange.bind(e.target)();
});

Or you can pass in the e.target like this classChange(e.target) and you use it like this:

function classChange(target){
    if($(target).hasClass('active')){
    } else { 
          $('.active').removeClass('active');
         $(target).next('p').addClass('active');
    }
}

Upvotes: 1

Related Questions