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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With