CSS manipulation in jQuery with if statement

Viewed 53
$(document).ready(function(){
  var width = $(window).width();
  $(function(){
    if ( width < 800 ) {
          $(".navbar-brand").css({'margin-left':'0'});
      }else{
          $(".navbar-brand").css({'margin-left':'100px'});
      }
  });
});

Hello, I know it's basic and I should not to ask about something so simple, but I have struggled by myself long enough. What I am trying to do is to remove margin-left in navbar when the viewport width is smaller than 800px, I can do it simply by adding a class, but I really want to learn how to manipulate css, with the jquery.

I appreciate all your advice, thank you.

3 Answers

Currently you're passing in an object to define the margin.

As an alternative, jquery uses "marginLeft" instead of "margin-left"

Give that a try.

Explanation : I have made a function changeScrSize(), which makes the changes in CSS properties. In ready event handler, the function is called, and sets the value of margin-left accordingly. Besides that, I have added a resize event handler, which modifies the value of margin-left when you resize the screen. So it is responsive :)

NOTE : Please view the output on full screen mode, to see the changes.

var width;

$(document).ready(function(){
  changeScrSize();
});

function changeScrSize(){
  let box = $('.navbar-brand');
  width = $(window).width();
  (width < 800) ? box.css("margin-left", 0) : box.css("margin-left", "100px");
}

$(window).on("resize", changeScrSize);
* {
  margin: 0;
  padding: 0;
}

.navbar-brand {
  background: red;
  width: 25vh;
  height: 25vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar-brand">
</div>

Try using the .css() method with attribute and empty value to remove that style.

$(".navbar-brand").css('margin-left','');
Related