How to prevent continuous clicks on the element? - javascript

I want to prevent continuous clicks on the button .toggler. When I click on it div is toggling properly, but if I click on it continuously many times div toggles many times until all the click events have not been completed.
The expectation is that if I click the button, its click event should be off until the div has not been toggled properly. After that its click should be on.
Click the button continuously many times to see the issue.
$(document).ready(function() {
$('.toggler').on('click', function(event) {
event.preventDefault();
$('.main-div').slideToggle('slow');
});
});
* {
margin: 0px;
box-sizing: border-box;
}
.main-div {
width: 80%;
float: right;
height: 200px;
background: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="toggler">Toggle</button>
<div class="main-div"></div>
The jQuery code I have tried is:
$(document).ready(function() {
$('.toggler').on('click', function(event) {
event.preventDefault();
var thisEement = $(this);
thisEement.off('click');
$('.main-div').slideToggle('slow', function(){
thisEement.on('click');
});
});
});
But that does not work as expected.
Any help would be appreciated <3.

The slideToggle has a callback function which is invoked when the operation is completed. So, you can introduce a new boolean variable that will be set to false when the operation starts and changed back to true when the toggle is completed.
$(document).ready(function() {
var flag = false;
$('.toggler').on('click', function(event) {
event.preventDefault();
if(!flag){
flag = true;
$('.main-div').slideToggle( "slow", function() {
flag = false;
});
}
});
});
* {margin: 0px; box-sizing: border-box;}
.main-div {width: 80%; float: right; height: 200px; background: #ddd;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="toggler">Toggle</button>
<div class="main-div"></div>

Try this,
$(document).ready(function() {
$('.toggler').on('click', function(event) {
event.preventDefault
$(".toggler").prop('disabled', true); // disable first
$('.main-div').slideToggle("slow", function() { // when slidetoggle ends
$(".toggler").prop('disabled', false); // enable button again.
});
});
});
jsfiddle demo
Hope helps,

Just use a boolean that will toggle when the slide starts and stops.
var inMotion = false;
$('.toggler').on('click', function(event) {
event.preventDefault();
if (inMotion == false) {
inMotion = true;
$('.main-div').slideToggle('slow', function() {
inMotion = false;
});
}
});
When the slideToggle() function finishes, that callback will run. The callback will set the boolean to false, allowing it to fire again.

Add the disabled attribute on click then remove it once the animation completes.
$(document).ready(function() {
$('.toggler').on('click', function(event) {
$(this).attr('disabled', 'disabled');
event.preventDefault();
$('.main-div').slideToggle('slow', function(){
$('.toggler').removeAttr('disabled');
});
});
});
* {margin: 0px; box-sizing: border-box;}
.main-div {width: 80%; float: right; height: 200px; background: #ddd;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="toggler">Toggle</button>
<div class="main-div"></div>

You can simply filter out the element while it's being animated and thus never queue up multiple toggles on it:
$('.main-div').not(':animated').slideToggle('slow');
No point in keeping track of this state yourself in some boolean when jQuery does it for you and lets you write functionally!
Full code (your original example modified):
$(document).ready(function() {
$('.toggler').on('click', function(event) {
event.preventDefault();
$('.main-div').not(':animated').slideToggle('slow');
});
});
FYI, your attempt would've worked if you properly re-bound the event handler function, but this is a much cleaner solution.

You can try this way...
$(document).ready(function() {
$('.toggler').on('click', function(event) {
$("#togglerButton").attr("disabled", "true");
$('.main-div').slideToggle('slow', function() {
$("#togglerButton").removeAttr("disabled");
});
});
});
* {
margin: 0px;
box-sizing: border-box;
}
.main-div {
width: 80%;
float: right;
height: 200px;
background: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="toggler" id="togglerButton">Toggle</button>
<div class="main-div"></div>
You can also do this by using event object pass to the click event. you can get count for number of time the click event performed. based on which you can set condition in javascript code and prevent multiple clicks like code given below.
$(document).ready(function() {
$('.toggler').on('click', function(event) {
if (!event.originalEvent.detail || event.originalEvent.detail == 1) {
$('.main-div').slideToggle('slow');
}
});
});

$(document).ready(function() {
var res = false;
$('.toggler').on('click', function(event) {
event.preventDefault();
if(!res){
res = true;
$('.main-div').slideToggle( "slow", function() {
res = false;
});
}
});
});
* {margin: 0px; box-sizing: border-box;}
.main-div {width: 80%; float: right; height: 200px; background: #ddd;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="toggler">Toggle</button>
<div class="main-div"></div>

Related

jQuery - multiple button clicks

My aim is for the users to click the button multiple times and on each click it changes the color and the wording on the button. I got the word and the color to change on the first and second click but it doesn't change when I click again. What am I doing wrong?
You can find my code below:
$(document).ready(function() {
$("button").click(function() {
$("#partyButton").text("Party Over!");
$(this).addClass("click").one("click", function() {
$("#partyButton").text("Party Time!");
$(this).removeClass();
});
});
});
button {
color: white;
font-family: 'Bungee';
background-color: #222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click {
background-color: #0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="partyButton" type="button"> party time!</button>
You can achieve this By using toggleClass and check with .hasClass()
//button
$(document).ready(function (){
$("button").click(function (){
$(this).toggleClass("click").text($(this).hasClass('click') ? "Party Time":"Party Over!");
});
});
button{
color: white;
font-family: 'Bungee';
background-color:#222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click{
background-color:#0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id = "partyButton" type = "button"> party time!</button>
Code Explanation:
$(this).toggleClass("click") this will toggle between class on each click
$(this).hasClass('click') check if this element has a class it return true/false .. you can also use it like if($(this).hasClass('click')){}else{}
() ? : ; shorthand if statment
Also Take care when you use removeClass() without assign any class it will remove all the classes for this element
The problem is you are registering an one time click event for the button while the button is clicked for the first time, which will detach the event once clicked. This is the reason you are not getting the event further. It is unnecessary and confusing
You just need the below implementation
$("#partyButton").click(function(){
if($(this).hasClass('click'))//check whether it party time or not
{
$(this).text("Party Time!").toggleClass('click');
}
else
{
$(this).text("Party Over!").toggleClass('click');
}
})
https://jsfiddle.net/n5hdg7tv/
For example:
$(function() {
$('#partyButton').on('click', function () {
var $button = $(this);
if($button.hasClass('click')) {
$button.removeClass('click').text('Party Time !');
} else {
$button.addClass('click').text('Party Over !');
}
})
});

How do I move an object 250px on first click and 250px back on second click

I have an object and when I click the button it moves 250px.
$(document).ready(function(){
$("#jqueryAirlinesBut").click(function(){
$("#flyingDroneImage").animate({right: '250px'});
});
});
Now when I click the button again I want it to move 250px back to where it was. I am new to jQuery and it seems like there are no if statements in that language? So what do I do this?
You should use a boolean variable to be able to track which click you're on.
See the example in the snippet.
$(document).ready(function() {
var firstClick = false;
$("#jqueryAirlinesBut").on('click', function() {
if (!firstClick) {
$("#flyingDroneImage").animate({
left: '+=250px'
});
firstClick = true;
} else {
$("#flyingDroneImage").animate({
left: '-=250px'
});
firstClick = false;
}
});
});
#flyingDroneImage {
width: 30px;
height: 30px;
background-color: blue;
position: absolute;
top: 50%;
left: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="jqueryAirlinesBut">Move</button>
<div id="flyingDroneImage"></div>
Why not just use a variable to manage state? Something like this:
var isClicked = false;
$(document).ready(function(){
$("#jqueryAirlinesBut").click(function(){
if(!isClicked){
$("#flyingDroneImage").animate({right: '250px'});
isClicked = true;
} else {
$("#flyingDroneImage").animate({right: '0px'});
isClicked = false;
}
});
});
Here is an Example which may help you:
$(document).ready(function(){
var moved=false;
$("button").click(function(){
if(moved===false){
$("div").animate({'margin-left': '250px'});
moved=true;
}else{
$("div").animate({'margin-left': '0'});
moved=false;
}
});
});
div{
width:50px;
height:50px;
background:#000;
margin-top:20px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Move</button>
<div></div>
save your state
$(document).ready(function(){
// save state
var isLeft = true;
// have a function that responds to state
var goTheOtherWay = function() {
var r;
if (isLeft) {
r = {left: '250px'};
} else {
r = {left: 0};
}
isLeft = !isLeft;
return r;
};
$("#jqueryAirlinesBut").click(function() {
// pass in your state-aware function to $.animate()
$("#flyingDroneImage").animate(goTheOtherWay());
});
});
#canvas {
postiion: absolute;
}
#flyingDroneImage {
background-image: url('http://rotorfx.com/wp-content/uploads/2015/12/large_large-3.jpg');
width: 150px;
height: 150px;
border: 1px solid gray;
background-size: 100%;
background-repeat: no-repeat;
background-position-y: 50%;
float: left;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="jqueryAirlinesBut">jqueryAirlinesBut</button>
<div id="canvas">
<div id="flyingDroneImage"></div>
</div>
$(document).ready(function(){
$("#jqueryAirlineBut").click(function(){
( $("#flyingDroneIMage").css('left') === '0px') ?
$("#flyingDroneIMage").animate({left: '250px'}) : $("#flyingDroneIMage").animate({left: '0px'});
});
});
#flyingDroneIMage{
position:relative;
right:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input type="submit" id="jqueryAirlineBut" value="Click to move"/>
<image id="flyingDroneIMage" src="http://lorempixel.com/400/200"/>
Something like this:
$(document).ready(function() {
var toggler = true; //keeps track of where to move
$("#jqueryAirlinesBut").click(function() {
$('#flyingDroneImage').animate({
right: toggler ? '-=250' : '+=250' //decides where to move based on the toggler
}, function() {
toggler = toggler ? false : true //switches the toggler
});
});
});
right: toggler ? '-=250' : '+=250'
The above is a ternary conditional operation.
It means: change the right property based on the following: if the toggler is true, the right property will have 250 pixels subtracted from the current right property, otherwise it will have 250 pixels added to it.
It could be written as
var amountToChange;
if(toggler == true){
amountToChange = '+=250'; //Adds 250 to the existing property
}else{
amountToChange = '-=250'; //Subtracts 250 from the existing property
}
The last function is a callback function, it gets called automatically when the animation finishes its last frame. You can also write that function somewhere else and pass it as the callback, and it will be executed when the animation ends.
You can read about it in the jQuery.animate documentation, it's the complete section

How to stop a parent's click event when the child's mousedown event is fired

As described in the title, I want to stop a parent's click event when the child's mousedown event is fired.
My HTML code looks like this
<div class='parent'>
<div class='child'></div>
</div>
my jquery code looks like this
$('.child').mousedown(function(){
//what can I write here to prevent parent's click event from fireing?
//I've tried event.stopPropagation() as well as
//event.stopImmediatePropagation() already
});
$('.parent').on('click',function(){...})
Mouse events are triggered like this way
MouseDown
Click
MouseUp
event.stopPropagation() in mousedown handler only affects on mousedown event. You can try this workaround:
var mdFaired = false;
$('.parent').click(function(e) {
if(!mdFaired) {
var counter = $(this).children('.counter');
var count = parseInt(counter.text());
counter.text(++count);
}
else {
mdFaired = false;
}
});
$('.child').mousedown(function(e) {
e.stopPropagation();
mdFaired = true;
var counter = $(this).children('.counter');
var count = parseInt(counter.text());
counter.text(++count);
});
div {
border: 1px solid black;
padding: 5px;
}
.parent {
width: 300px;
height: 300px;
}
.child {
width: 50%;
height: 50%;
margin: 50px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<span class="counter">0</span>
<div class='child'>
<span class="counter">0</span>
</div>
</div>
e.stopPropagation();
e.preventDefault();
e is event passed from function call.
Should do the trick.

How to close this menu clicking outside?

I have this menu:
CSS
#message {
display: none;
position: absolute;
width: 120px;
background: #fff;
color: #000;
font-weight: bold;
}
When I click in it opens #message.
My problem is to close this thing.
JS:
$(function() {
$("#subm").click(function(evt) {
$("#message").css({
top: 55,
left: evt.pageX - 55
}).show();
});
});
I try to put this code inside function above:
$('html').click(function(evt) {
if($('#message').is(":visible")) {
$('#message').hide();
}
});
but nothing is happening, apparently menu is opening and closing in the same time.
What is wrong? how can I close this menu clicking outside message box or even in span class?
JSFiddle
You can bind a click handler to the document to close it:
Example: https://jsfiddle.net/jmpf1usu/4/
$("#subm").click(function(evt) {
$("#message").css({
top: 55,
left: evt.pageX + 55
}).show();
evt.stopPropagation();
});
$(document).click(function(){
$("#message").hide();
});
evt.stopPropagation()is required so that the click never reaches the document, thus immediately triggering it to close again.
Try changing your js to this:
$("#subm").click(function() {
$("#message").show();
});
$("#message").mouseleave(function(){
$("#message").hide();
});
When the user hits the button the menu will open. When the user mouse leaves the div it will hide it. Is that what you're looking for?
If you really want a click to remove the visibility you can do:
$("body").on('click',function(){
$("#message").hide();
});
I just prefer the mouse leave, tbh.
You can use the below code for hide message
$(function() {
$("#subm").click(function(evt) {
$("#message").css({
top: 55,
left: evt.pageX + 55
}).show();
});
$(document).click(function(event) {
if (!$(event.target).is("#subm")) {
$("#message").hide();
}
});
});
#message {
display: none;
position: absolute;
width: 120px;
background: red;
color: #fff;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subm">open</span>
<div id="message">
message
</div>
please try with below code snippet.
$(function() {
$("#subm").click(function(evt) {
evt.stopPropagation();
$("#message").css({
top: 55,
left: evt.pageX + 55
}).show();
});
$('html').click(function() {
$("#message").hide();
});
});
JSFiddle
Try this:
$(function () {
$("#message").click(function (evt) {
evt.stopPropagation();
});
$("#subm").click(function (evt) {
evt.stopPropagation();
$("#message").css({
top: 55,
left: evt.pageX + 55
}).toggle();
});
$('html').click(function (evt) {
if ($('#message').is(":visible")) {
$('#message').hide();
}
});
});
#message {
display: none;
position: absolute;
width: 120px;
background: red;
color: #fff;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subm">open</span>
<div id="message">message</div>
You can simply use .hide to hide that element. Add an event listener for #message and do the following:
$("#message").click(function(evt) {
$("#message").hide();
});
I put a working example here:
https://jsfiddle.net/jmpf1usu/8/
To do it without stopPropagation() shenanigans you can add the following:
$(document).ready(function(){
$(document).click(function(event) {
if(event.target.id != "message"
&& event.target.id != "subm"
&& $('#message').is(':visible'))
{
$('#message').hide();
}
});
});
This is set up so that if the user clicks anything that is not the #message and is not the #subm open span, the message div will hide.
Expanded your fiddle: https://jsfiddle.net/jmpf1usu/10/
Good luck :).

Hidden anchor link falling in next line once show

Can you tell me why the anchor link with class "edit" falling in next line the next time it is being displayed/showed?
To replicate click, edit button and then save button on jsfiddle link below.
JS Fiddle
HTML
<div id="con">
Delete
Edit
Save</div>
JQUERY
$(".edit").click(function(){
var ID=$(this).attr('id');
var RemoveIDedit = ID.replace('edit_','');
$(this).hide();
$("#save_"+RemoveIDedit).show();
});
$(".save").click(function(){
var ID=$(this).attr("id");
var RemoveIDsave = ID.replace('save_','');
$(this).hide()
$("#edit_"+RemoveIDsave).show();
Demo
instead of this
$("#edit_"+RemoveIDsave).show();
Try this
$("#edit_"+RemoveIDsave).css("display","inline");
Remove position:absolute for .edit and .save from your stylesheet.
This is due to display: block;, replace it with display: inline;
Please use following code, I've edited this
$(document).ready(function() {
$(".edit").click(function() {
var ID = $(this).attr('id');
var RemoveIDedit = ID.replace('edit_', '');
$(this).hide();
$("#save_" + RemoveIDedit).css('display', 'inline');
});
$(".save").click(function() {
var ID = $(this).attr("id");
var RemoveIDsave = ID.replace('save_', '');
$(this).hide()
$("#edit_" + RemoveIDsave).css('display', 'inline');
});
});
.save {
display: none;
}
.save,
.edit {
position: absolute;
padding-left: 5px;
}
#con {
width: 500px;
height: 500px;
border: 1px solid;
boreder-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="con"> DeleteEdit Save
</div>a
You can use the Visibility property instead of display
css
.save {
visibility:hidden;
}
.save, .edit {
position: absolute;
padding-left: 5px;
}
jquery
$(document).ready(function() {
$(".edit").click(function(){
var ID=$(this).attr('id');
var RemoveIDedit = ID.replace('edit_','');
$(this).css("visibility","hidden");
$("#save_"+RemoveIDedit).css("visibility","visible");
});
$(".save").click(function(){
var ID=$(this).attr("id");
var RemoveIDsave = ID.replace('save_','');
$(this).css("visibility","hidden");
$("#edit_"+RemoveIDsave).css("visibility","visible");
});
});
Hope this may satisfy you

Categories