Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Question about jQuery .hasClass()

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #151629
    Rugg
    Participant

    Is there is a more efficient way to write $(this).hasClass('myclass') inside a click function? Below is a reference to the code in question , including a working sample…Any help is appreciated. Thank you.

    $('.button').click(function () {
    
        if ($(this).hasClass('red')) {
    
            alert('Red Works');
    
        } else if ($(this).hasClass('blue')) {
    
            alert('Blue Works');
    
        } else if ($(this).hasClass('green')) {
    
            alert('Green Works');
    
        }
    
    });
    

    Working Sample: http://jsfiddle.net/eNhQT/

    #151659
    TheDoc
    Member

    Really difficult to say without fully knowing what the code is trying to accomplish.

    For starters, I’d be storing $(this) as a variable just inside the click function like this:

    var button = $(this);
    

    …and then going:

    button.hasClass('whatever')
    

    Depending on what you’re trying to do you might want to look into using a switch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.