Andy Smith
Andy Smith

Reputation: 619

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

I'm developing a carousel style slider and want to hide one of the controls once the left margin of the ul equals -3480px. Here's my code:

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

It's not doing anything though and I'm not sure what to do next. Has anyone got any pointers or suggestions?

Upvotes: 3

Views: 212

Answers (5)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Based on what style property you are animating you should check that. Also make sure that convert the value into int before comparing because css() method will give the unit(px/em..) also along with its value.

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

If you are executing this code on any animation callback then I would suggest you to check for <= instead of == because the value may not be that perfect during animation. Try this.

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

Upvotes: 1

Taylor Rose
Taylor Rose

Reputation: 763

I don't have your full script to play with but I would recommend doing a console.log() on $("ul#listName").css("margin-left") to see if that actually outputs what you think it does. I would also use <= in case you're not hitting that exact value.

I'm just working off assumptions here but hopefully that will help.

Upvotes: 1

Crsr
Crsr

Reputation: 624

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

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

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

I used parseInt to show an alternative and avoid any hangups you may have if/when px is suffixed.

Upvotes: 1

s_p
s_p

Reputation: 4693

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

Upvotes: 1

Related Questions