Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two functions on button clicks

function myFunction() {
  document.getElementById("tt").style.marginTop = "50px";
  document.getElementById("tt").style.marginTop = "80px";  
}
<div class="switcher" style="margin-top: 30px;background-color: #430000;width: 300px;height: 300px;" id="tt">
  <button id="quick-search-switcher" type="button" onclick="myFunction()">Find a doctor</button>
</div>

I need some help here my code to let the button on the first click margin-top the container div 30px and on the second click -30px but it is not working please help me with this code.

like image 826
Bataineh Avatar asked Oct 18 '22 03:10

Bataineh


2 Answers

I am a fan of jQuery.

This is my solution (by using 2 classes and toggling them):

$('#quick-search-switcher').click(function () {
  $('.switcher').toggleClass('first').toggleClass('second');
});
.first {
  margin-top: 60px;
}

.second {
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switcher first" style="background-color: #430000; width: 300px; height: 300px;" id="tt">
  <button id="quick-search-switcher" type="button">Find a doctor</button>
</div>
like image 58
jack Avatar answered Oct 21 '22 01:10

jack


You could use a flag to indicate which action you want to perform and move it up or down accordingly.

var switcherAtTop = true;
var elem = document.getElementById('tt');

elem.addEventListener(
  'click',
  function() {
    if(switcherAtTop) {
      document.getElementById("tt").style.marginTop = "80px";
      switcherAtTop = false;
    } else {
      document.getElementById("tt").style.marginTop = "50px";
      switcherAtTop = true;
    }
  }
)
.switcher {
  margin-top: 30px;
  background-color: #430000;
  width: 300px;
  height: 300px;
}
<div class="switcher" style="" id="tt">
  <button id="quick-search-switcher" type="button">Find a doctor</button>
</div>

That said, depending on your use case it may be a bit confusing for users if one button does multiple things. You might be better off having two buttons, with different event listeners (and label text). Then you can just show and hide them as required.

like image 41
elvey Avatar answered Oct 21 '22 00:10

elvey