Jquery if loop with css

Asked

Viewed 73 times

2

$('#label-user').click(function(){
    if ($('#label-user').style.display != 'none') {
        $('#label-user').css('display', 'none');
    }       
});

good, the jquery can’t read the part $('#label-user').style.display != 'none', and I don’t know how to replace it with something that jquery recognizes, I searched its documentation, but I couldn’t find anything

1 answer

2


The syntax .style.display is for native Javascript, as you would be using jQuery .css('display') != 'none'.

You can also do everything native inside the callback:

$('#label-user').click(function(){
    if (this.style.display != 'none') {
        this.style.display = 'none';
    }       
});

Or using jQuery with .hide():

$('#label-user').click(function(){
    $(this).hide();     
});

Actually, I think that would be enough

$('#label-user').click(function(){
     this.style.display = 'none';     
});

because a hidden element cannot click anyway...

  • 1

    so q release give as the right answer, vlw man :D

  • 1

    A note, if you don’t want to use . toggle(), which shows when clicking, and hides when clicking again. Use . Hide(), which only enables the hide process.

  • 2

    @Thiagoyoithi is not possible to click an element with display: none;.

  • 1

    @Sergio, yes, exactly for that. I’m giving the alternative of Hide() by making more sense in the context that he presented. Why would he use . toggle() in a click event where the target is $(this)itself? Considering he won’t be able to click again after he’s already hidden? It makes more sense to use Hide(), as it will simply hide the element, without allowing more interactions to this button (which will no longer be on the screen anyway). It was just something that crossed my mind here, rsrsrs... correct me if I’m missing something.

  • @Thiagoyoithi the .hide() also makes display: none; -> https://jsfiddle.net/trpqrjpb/

  • @Sergio, yes I know, all these functions, show(), Hide(), toggle(). They all make use of the display:None; css property. That’s not my point. My point is that it makes no sense to use toggle() on an element that might get hidden, as it will not be possible to reactivate it (this being a $(this target click event)).

  • 2

    @Thiagoyoithi ah, I understand, you’re right, semantically it’s more correct to use the .hide(), is that right? I’ll correct.

  • @Sergio Exactly! Thanks for understanding.

  • 1

    @Thiagoyoithi thanks for the patience :P here is already night and tiredness makes the head slower :)

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.