How can I hide an element using jQuery based on the value of its margin-left in CSS?

I am developing a carousel style slider and want to hide one of the controls when the left margin ul

is -3480px. Here's my code:

$(function(){
    if($("ul#listName").css("margin-left") == "-3480px"){
      $(".nextButton").hide();
    }    
});

      

It doesn't do anything and I'm not sure what to do next. Anyone got any directions or suggestions?

+3


source to share


5 answers


Depending on which style property you are animating, you should check this. Also make sure to convert the value to int before comparing, because the method css()

will give one (px / em ..) along with its value as well.

    if(parseInt($("ul#listName").css("margin-left"), 10) == -3480){
        $(".nextButton").hide();
    }    

      



If you are executing this code in any animation callback, I suggest you check <=

instead ==

, because this value might not be perfect during animation. Try it.

    if(parseInt($("ul#listName").css("margin-left"), 10) <= -3480){
        $(".nextButton").hide();
    }  

      

+1


source


var mm = $("ul#listName").css("margin-left");
if(mm == -3480+"px"){
  $(".nextButton").hide();
}

      



+1


source


var leftMargin = parseInt($('ul#listName').css('margin-left'), 10);
if (leftMargin == -3480){
  $('.nextButton').hide();
}

      

I used parseInt

to show an alternative and avoid any freezes that might occur if / when the px

suffix.

+1


source


var p = $(".your_class");
var position = p.position();
  if(p.position().left == '-3480px'){
$(".nextButton").hide();
}

      

+1


source


I don't have your complete script, but I would recommend doing console.log()

on $("ul#listName").css("margin-left")

to see if it actually outputs what you think. I would also use <= in case you haven't reached this exact value.

I'm just working on the assumptions here, but hope this helps.

+1


source







All Articles