Two functions at the touch of a button

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>
Run codeHide result

I need some help here, my code is to have the button on the first mark of click at the top of the container div 30px and on the second click -30px, but it does not work, please help me with this code.

+4
source share
3 answers

You can use the 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>
Run codeHide result

However, depending on your use case, this can be a bit confusing for users if one button performs several actions. You might be better off with two buttons, with different event listeners (and shortcut text). Then you can simply show and hide them as needed.

+1

jQuery.

( 2 ):

$('#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>
Hide result
+1

You can generally solve this problem by wrapping an array of functions that you would like to alternate (two in your case, but it can be any number) in a function that will call the module on the number of attempts to call a new function.

This will work with parameterized functions if all the functions you pass accept the same 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.
0
source

Source: https://habr.com/ru/post/1688977/


All Articles