Ario MD Ario MD - 7 months ago 11
Javascript Question

How can i add elements events without jquery?

How can i add elements events without jquery ?

Could someone help me to write this code without jquery please

Some btn clicked and when clicked move down.

Thank you in advance.



$('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>




Answer

You can select elements with document.querySelectorAll and make a loop for access all elements

and use addEventListener('click', function(){ //code ... }); for click events

look at final code

var btns = document.querySelectorAll('button.btn');

var clickFn = function(){
  this.style.marginTop = '100px';
};

for(var i=0; i<btns.length; i++){
  btns.item(i).addEventListener('click', clickFn);
}
button.btn {
  display: inline-block;
  float: left;
  margin-left: 5px;
}
<!DOCTYPE html>
<html>
<head>
  <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>