Ario MD Ario MD - 7 months ago 17
Javascript Question

jQuery this element refer to all element?

In this code i use $(this), but all element move down

$('button.btn')
refer to all btn but in click event i use
$(this)
then only one btn must moved down!

Why this happened ?



$('button.btn').click(function (){
$(this).css({
'margin-top': '100px'
});
});

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="parent">
<button class="btn">Lorem.</button>
<button class="btn">Aut.</button>
<button class="btn">Labore.</button>
<button class="btn">Consectetur.</button>
<button class="btn">Adipisci?</button>
</div>
</body>
</html>




Answer

Its not a jquery issue its about your css

When you add margin-top to a inline-block element all parent element move down and you think all btns have margin-top

$('button.btn').click(function (){
  $(this).css({
    'margin-top': '100px'
  });
});
button.btn {
  display: inline-block;
  float: left;
  margin-left: 5px;
}
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="parent">
    <button class="btn">Lorem.</button>
    <button class="btn">Aut.</button>
    <button class="btn">Labore.</button>
    <button class="btn">Consectetur.</button>
    <button class="btn">Adipisci?</button>
  </div>
</body>
</html>