Two functions on button clicks

Viewed 89

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.

3 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>

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.

You can generically solve this problem by wrapping an array of functions that you would like to alternate through (two in your case, but it could be any number) in a function that will invoke the modulus of the count of the number of times the new function has been invoked.

This will work with parameterized functions, provided all the functions you pass will accept similar parameters.

function alternate(arrayOfFunctions) {
    var counter = 0;
    return function() {
       var f = arrayOfFunctions[counter++ % arrayOfFunctions.length];
       return f.apply(this, arguments);     
    }
}

function doA() { console.log(doA.name);}
function doB() { console.log(doB.name);}
function doC() { console.log(doC.name);}

var newFunction = alternate([doA,doB,doC]);

newFunction();  // calls doA
newFunction();  // calls doB
newFunction();  // calls doC
newFunction();  // calls doA again, etc.
Related