jQuery click if else only fires once and not when clicked - javascript

I am trying to create a mobile menu that has a burger menu, and when you click that menu, it should slide up and down. Before I implement this, I am testing how the jQuery code would work and I can only get it to console log when the page loads and not when you click the actual button.
jQuery:
function mobileMenu() {
$('.mobile-menu-button').click(function() {
$(this).data('clicked', true)
});
if ($('.mobile-menu-button').data('clicked')) {
console.log("Clicked!")
} else {
console.log("Not Clicked!")
}
};
mobileMenu();
For some reason it only console logs 'Not Clicked!' when you load up the page. But it isn't responsive when you actually click the button.

Into your function you add handler for a button. It set data-clicked to true only when you click on it.
Checking for data('clicked') executed immediately. If you set this param like into next code
<button class="mobile-menu-button" data-clicked="true">Click me</button>
you will receive into console "Clicked!".
In the next case
<button class="mobile-menu-button">Click me</button>
you will receive "Not Clicked!"

You are only performing the console.log once, when the mobileMenu() function is called. Simply updating the data inside the event handler will not cause the function to fire again, you need to explicitly put the function call inside your event handler, either by moving the event handler outside of the function, or having it call a different function, like so:
function logger() {
if ($('.mobile-menu-button').data('clicked')) {
console.log("Clicked!")
} else {
console.log("Not Clicked!")
}
}
function mobileMenu() {
$('.mobile-menu-button').click(function() {
$(this).data('clicked', true)
logger();
});
logger();
};
mobileMenu();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mobile-menu-button">Button</button>

Related

Choose only the first button

I'm trying to do that only one can happen, if you click yes or no. As it is now if you click "no" in the first time and "yes" in the second time, it will execute it twice .
function confirm() {
$("#no").one("click", function(){
return false;
});
}
$("#yes").one("click", function () {
//do something
});
thanks for help
Both events are attached at document.ready I assume, which means they will remain active indefinitely unless you specify otherwise.
The following approach is fairly basic, just set a variable 'hasClicked' to false. And as soon as either one of them is clicked, set 'hasClicked' to true. Each button has an if-structure that only executes the code IF 'hasClicked' is false.
Try the following:
var hasClicked = false;
function confirm(){
$("#no").one("click", function(){
if (!hasClicked){
hasClicked = true;
return false;
}
});
$("#yes").one("click", function () {
if (!hasClicked) {
hasClicked = true;
//do something
}
});
}
As you can't unbind an event binded with one() check this answer
So you'll have to work around like this:
function confirm() {
$("#no").bind("click", function(){
$(this).unbind(); // prevent other click events
$("#yes").unbind("click"); // prevent yes click event
// Do your stuff
});
}
$("#yes").bind("click", function () {
$(this).unbind();
$("#no").unbind("click");
// Do your stuff
});
Assign your buttons a class called confirmation. Set a event handler based on class. Read the value of the button to decide what you want to do.
$(".confirmation").one("click", function(){
if($(this).val() === 'yes'){
//do something
}else{
return false;
}
}

Perform click event for only one button under a CSS class

I have some JavaScript to execute logic i.e. doSomething() when a button is clicked. I know the class of the buttons, but there are multiple buttons on the page with this same class. The problem with my code below is that the doSomething() function is executed once for every button on the page when I only want it to execute one time only.
var myButtonClass = $(".my-button-class");
if (myButtonClass) {
myButtonClass.click(function (event) {
if (someCondition) {
doSomething();
}
});
}
I know it would be better to select by button div, but the button div names all vary based on how many there are (i.e. #my-button-div1, #my-button-div2, etc.) and the number of buttons is indefinite.
Is there a way to only do this event once? I don't care which button in the class happens to be clicked, I just need the event to fire once and then it's done.
UPDATE: To be clear, I still want the logic to execute if the user clicks another button on the page again, so I don't want to completely unbind the event. I just don't want it to execute once for every button on the page. For example, let's say I have 4 buttons. Right now it's doing something like the following when just one button is clicked:
alert!
alert!
alert!
alert!
I only need ONE of those alerts. Basically, whenever the user clicks any of the buttons on the page, I need it to go alert! only once per click.
Revised so that you don't have weird if statements, and allows for other click handlers to happily work if binded elsewhere
UPDATED:
var clickHandler = function handleClick(event) {
doSomething();
}
var bindClicks = true;
function doSomething() {
alert('alert!');
}
function doTheBinding() {
if (bindClicks) {
$('.my-button-class').on('click', clickHandler);
bindClicks = false;
}
}
// as many times as you want but it will still call once
doTheBinding();
doTheBinding();
doTheBinding();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
You can use on() and off() to bind and unbind the event on an element respectively.
$('.my-button-class').on('click', function (event) {
if (someCondition) {
doSomething();
// Unbind the event on all the elements having the class
$('.my-button-class').off('click');
// To unbind the event on only the clicked element
// $(this).off('click');
}
});
Sidenote: if (myButtonClass) { will always evaluate to true. jQuery returns an object even when the element is not found and an object is always truthy. To check if an element exists in DOM, use length property on the jQuery object $('someSelector').length > 0.
If you give the handler a local boolean variable that is protected with a closure, you can create a function that will execute only once. See this SO answer.
Run the code snippet below to see it in action.
$(".my-button-class").click(function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
doSomething();
}
};
}());
function doSomething() {
alert("You should only see me once!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
UPDATE: To address a different issue of the click event getting bound more than once. Just do a similar thing with:
var bind = function() {
var bound = false;
return function() {
if (!bound) {
bound = true;
$(".my-button-class").click(function() {
if (someCondition)
doSomething();
});
}
};
}();
bind();
bind(); // won't execute second time
var someCondition = true;
function doSomething() {
$("#output").append("<br>alert!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
<span id="output"></span>

Wait for user confirmation before triggering event

I'm trying to figure out how events works and how to wait for a second event to trigger before the original event is being executed.
$.fn.customConfirm = function (message){
// Create modal
// then ...
$(confirmModal).find("modal-footer a").click(function(e2){
e2.preventDefault();
return ($(this).hasClass("dialogConfirm")); // Returns true if option has class dialogConfirm
});
};
$("a[data-confirm]", click(function(e){
if (!$.customConfirm($(this).attr("data-confirm")))
return false; // Only if customConfirm returns false
// Continue
});
This works like a charm. customConfirm creates a bootstrap modal with 2 buttons (confirm/cancel) and sets the data-confirm attribute value as the modal-body html.
What I don't know how to solve is how to handle the event e based on the user interaction with the modal. As of now it just shows the modal dialog and the original event seems to do nothing.
I solved it by adding the attribute data-confirmed to the clicked element if the user confirms and then triggering a second click() on the original element.
$.fn.customConfirm = function (message){
var handle = $(this);
// Create modal
// then ...
$(confirmModal).find("modal-footer a").click(function(e2){
e2.preventDefault();
$(handle).attr("data-confirmed", ($(this).hasClass("dialogConfirm")))[0].click();
return false;
});
};
$("a[data-confirm]").click(function(e){
if ($(this).attr("data-confirmed") !== "true")
{
e.preventDefault();
$(this).customConfirm();
return false;
}
$(this).removeAttr("data-confirmed");
// Continue
});

Why are my functions triggering on page load and what can I do about it?

I have the following javascript. For eample the console.log('test')triggers when I load the javascript. I expect it to trigger when I click a button with the class login. What am I doing wrong?
$(document).ready(function() {
switchImage(5000, '#top .images');
switchImage(5000, '#top .feature-text');
$('.login input').focus(function(){
$('.login .hidden').removeClass("hidden");
$('.login [type=text]').removeClass("span2").addClass("span3");
});
$('.loginbutton').click(login());
});
function login(){
event.preventDefault();
console.log('test')
}
function switchImage(wait, element){
//Fades out first element and put's it in the bottom of the stack
$(element+'>*:first-child').delay(wait).fadeOut('slow', function() {
//fade in imag2
$(element+'>*:nth-child(2)').fadeIn('slow');
$(element+'>*:first-child').appendTo(element);
switchImage(wait, element);
});
}
You have:
$('.loginbutton').click(login());
This says "When the button is clicked, invoke the result of login().
What you want is:
$('.loginbutton').click(login);
Which is "When the button is clicked, invoke the login function".

Why doesn't this execute on first click?

In this jsFiddle
http://jsfiddle.net/littlesandra88/RBU8K/
have I the following code
function addRemove(id) {
alert("1");
$('#'+id).toggle(function() {
alert("2");
$('#'+id).after('<tr id="details" ><td>It worked</td></tr>');
}, function() {
alert("3");
$("#details").remove();
});
}
When clicking one time on "Details" it prints "1", but not "2" for some reason.
When the first click have been done, it works like it is supposed to.
But what's wrong, since the first click doesn't print out "2"?
And how can it be fixed?
Update
This is the solution
function addRemove(id) {
if ($('#accTable').find("[id*='details']").length == 0) {
$('#'+id).after('<tr id="details" ><td>It worked</td></tr>');
} else {
$("table tr").remove("#details");
}
}
You are only attaching a event handler (the toggle thingy) when calling addRemove(), then after you click again the event handler gets triggered.

Categories

Resources