Else doesn't seem to be running

I am a complete beggar and was hoping to get some help in my first script.

Basically, I want one link to be clicked to slide down and change the link text, when it clicks again, the process will change.

here is my code:

$(function() {
if ($('#link1:contains("link text")')) {
        $('#link1').click(function() {
            $('#div1').slideDown(2000);
            $('#link1').text('hide div 1');
        }); 
}
else {
        $('#link1').click(function() {
            $('#div1').slideUp(2000);
            $('#link1').text('link text');
        }); 
}
});

Any help would be appreciated, thanks guys.

+3
source share
4 answers

if ($('#link1:contains("link text")')) {will always be true. JQuery will always return an object. What you need to change is:

if ($('#link1:contains("link text")').length>0) {
+7
source
$function(){
    $('#link1').click(function() {
        if($('#link1:contains("link text")').length){
            $('#div1').slideDown(2000);
            $(this).text('hide div 1');
        } else {
            $('#div1').slideUp(2000);
            $(this).text('link text');
        }
    });
});

As I understand it, you need to evaluate the text every time you press the button. It will do it.

+3
source

An Object JavaScript. -, .

, jQuery , length.

+1

, , .

jQuery, , , !![] - true, else, if is true.

,

if ($('#link1:contains("link text")')[0]) {
    ...

because if no elements are found, the first value will be undefined, which evaluates to false.

0
source

All Articles