$(function() {
$('#btn').click(function() {
$('#inp').focus();
console.log('two');
});
$('#inp').focus(function() {
console.log('one');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">
Click
</button>
<input type="text" id="inp">
If you run the above snippet in Chrome the out put will be
one
two
When you run in IE the out put is
two
one
How to make it synchronous in IE?
The solution is to use triggerHandler method.
.triggerHandler() returns whatever value was returned by the last
handler it caused to be executed. If no handlers re triggered, it
returns undefined
console.log('two') will only run when focus event is finished.
$(function() {
$('#btn').click(function() {
$('#inp').triggerHandler('focus');
console.log('two');
});
$('#inp').focus(function() {
console.log('one');
});
});
Related
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>
I have this button:
<button
type="button"
onclick='parent.parent.ExecuteCommand(14);event.stopPropagation()'
class="button_air-medium">
<img
id="selectMode"
class="shortcutContant"
src="../stdicons/icon_select.gif">
</button>
As you can see inside onclick attribute I call 2 functions ExecuteCommand and stopPropagation.
The execute command works fine but it seem to me that stopPropagation method is not fired because the element under the button is influenced.
Any idea why stopPropagation method is not working?
There is likely no eventavailable to the inline handler in the browser you are using
You will have an easier time if you do
$(function() {
$(".button_air-medium").on("click",function(e) {
e.stopPropagation();
parent.parent.ExecuteCommand($(this).data("commandnumber"))
// or return false here
});
});
using
<button type="button" data-commandnumber="14"
class="button_air-medium"><img id="selectMode" class="shortcutContant"
src="../stdicons/icon_select.gif"></button>
If you want to stop the image from handling events you could try
$(function() {
$(".button_air-medium").on("click",function(e) {
e.stopPropagation();
parent.parent.ExecuteCommand($(this).data("commandnumber"))
// or return false here
});
$(".button_air-medium > img").on("click",function(e) {
$(this).parent().click();
return false;
});
});
or find where it is handled and edit that handler
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>
I have problem with javascript,
in my html code:
<input onclick="myFunction();" />
<script>
function myFunction(){
//excecution of this fucntion
}
</script>
After clicking the input, the function runs. But I want myFunction to be disable after the first click, so when I click again, myFunction won't run.
Just remove the attribute
<input onclick="myFunction(this);" />
<script>
function myFunction(elem){
// code here
elem.removeAttribute('onclick')
}
</script>
or even better use event listeners
<input id="myInput" />
<script>
document.getElementById('myInput').addEventListener('click', myFunction, false);
function myFunction(elem){
// code here
this.removeEventListener('click', myFunction);
}
</script>
One way is to set it to a empty function, after the code has executed.
function myFunction(){
//(..) Some code
myfunction = function(){}; // empty the function so nothing happens next time
}
If you're using jQuery (as You have included it in the tags), I'd go with .one():
<input type="txt" class="my-input" />
function activateClick(){
// single click:
$('.my-input').one('click', function(){
// do stuff ...
});
}
// Activate single click on input element
// Can be reactivated later on, using the same function (see DEMO):
activateClick();
DEMO
Use a boolean indicator to determine whether the function has already run or not. The advantage with this method is that it is easy to reset the function status at a later date.
<!DOCTYPE html>
<html>
<body>
<button onclick='func();'>Function</button>
</body>
<script>
var funcActive=true;
function func() {
if (funcActive) {
funcActive=false;
alert('func ran');
}
}
</script>
</html>
I'm dynamically binding event to a text element. This is my code:
<input type="text" id="myTxt" />
<script type="text/javascript">
function attachEvent1(element){
element.keyup(function(){
console.log("Event:"+event.keyCode);
});
}
function attachEvent2(element){
element.keyup(function(){
console.log("Value:"+this.value);
});
}
attachEvent1($('#myTxt'));
attachEvent2($('#myTxt'));
</script>
What I need it, I want the second event handler (attched by attachEvent2) to get called first, even if it is binded after attachEvent1.
Is it possible in jQuery?
What about something like this:
function handler1()
{
console.log("Event:"+event.keyCode);
}
function handler2()
{
console.log("Value:"+this.value);
}
function attachEvent1(element)
{
element.keyup(handler1);
}
function attachEvent2(element)
{
element.unbind('keyup', handler1);
element.keyup(handler2);
element.bind('keyup', handler1);
}
attachEvent1($('#myTxt'));
attachEvent2($('#myTxt'));
If you want something fancier, you could keep a list of the handlers, and do the rebinding in a loop, etc. but this basic idea of re-binding the events, has the desired effect.