I'm creating a simple app using JS/jQuery as a learning exercise and am running into a problem I've encountered before and can't seem to solve. Why, in the following code, is the second click event triggered automatically rather than when I click $('.tweet li a.username')?
$(function(){
setInterval(update, 3000);
$('.showMore').on('click', function() {
moreIndex += 5;
update();
})
$('.tweet li a.username').on('click', alert('hey!'));
});
alert('hey!') is filler for a function I'm still working out. How should this be organized so that the click event triggers when the link is clicked rather than when the page loads? The $('.showMore') event works properly, even if I change the order.
it is because you are invoking the alert function there instead of passing the callback function reference.
In your case you are invoking the alert() function and pass the value returned by the alert as the click event handler.
$('.tweet li a.username').on('click', function(){
alert('hey!')
});
You need to wrap the alert in a callback function, just like the first example:
$('.tweet li a.username').on('click', function() { alert('hey!') });
The .on method is expecting a JavaScript object in that position, a function in particular, which it can execute later. What is happening in your original code is that the JavaScript engine is looking for a function, but sees some other code there instead -- so it executes the code there (activating the alert) in hopes that a useful object will be returned. (When nothing is returned, the JavaScript engine instead assumes that you want null to be executed on a click event, and happily does so.)
Related
I am very new to Javascript and I am trying to create a simple button, that when clicked will refresh the page (reload the game). I wrote the below code and when I inspect the button in Chrome, there are no event listeners attached to it.
var replay = function() {
var replayButton = getElementById('play-Again');
replayButton.addEventListener('click', window.location.reload());
document.getElementById('play-again').appendChild(replayButton);
}
<button id="play-Again">Play again?</button>
To fix your code, you need to give the event listener a function. Currently your are giving it the response of calling a function, not an actual function value. Here is revised code for your addEventListener
replayButton.addEventListener('click', function () {
window.location.reload()
});
If you want just a simple reload button, you can use this:
<button id="play-again" onclick="window.location.reload()">Play again?</button>
Otherwise: The EventListener must be executed when the js file is loaded, which it doesn't on your code because you placed it into a function that you probably never call! So you either put the EventListener outside of the function or you call the function somewhere.
Plus, the last line where you call ...appendChild(...) doesn't seem right.
The live function of jQuery is triggered with an event
The api documentation is here
http://api.jquery.com/live/
$(".xyz").live('event', function(){
});
I want the above function to run without an event , i.e as soon as the class xyz is dynamically created.
I have tried this without the event parameter
$(".xyz").live( function(){
});
but it doesn't work !!
adding
I don't know exactly what you want to do, but I'll make assumptions.
Scenario 1
In order to execute a function inside jQuery, you need to tell jQuery when to execute the function, otherwise it cannot know. One way to do this is:
$(document).ready(function () {
$('.xyz').css('color', 'red');
// more code, anything, functions, calculations, etc.
});
The code inside that function will be executed as soon as your DOM is ready (is safe to manipulate).
You can put $('.xyz').css('color', 'red'); also outside the ready() event and it will also be executed. The "event" this time is when the executions of the page reaches that line of code. For example, if you put this line before your HTML, you don't have guarantee it will work.
Scenario 2 - onClassChange event
If you are looking for an event called something like onClassChange, it does not exits on jQuery. An approach to that problem could be this:
Create a timer which runs infinitely
On each run, check if that object has your class ( $(obj).hasClass('xyz') )
If yes, do whatever you want to do inside the if ()
Also, since you said the class xyz is created dynamically, you can try to run your function immediately after you create your class in your code.
For more about onClassChange event, there are long discussions you can check on this site.
I am creating a simple quiz kind of page. So I created grid with element.
Here is the div which has the grid cloned.
Var template = $(".answer-layout-").clone();
And the listener for the element in loop is
$("a", template ).click(this.Answer_PickOne_OnClick(item));
The function implementation is,
this.Answer_PickOne_OnClick = function (sender, e) {}
I expect the click action to get trigger when i click the clement. But it is getting triggered on execution of the code.
Tried many ways by passing argument and so but fails. Any suggestion please
This is because code this.Answer_PickOne_OnClick(item) actually executes your function. If you want to hook it as event handler instead, you should wrap in in a function:
$("a", template ).click(function() {
this.Answer_PickOne_OnClick(item);
});
I have some html on my page, and in my head I have $("#someelement").click(alert("click"));. Whether #someelement exists or not, when I load the page for some reason the alert goes off. However, it doesn't execute when I have $("#someelement").click(function(){alert("click")});. Why is that?
alert("foo") will always alert foo immediately, it does not return a function that you can pass as an event handler. You need to pass a function into the jQuery event binding method instead.
$("#someelement").click(function(){
alert("click");
});
Additionally, if this code is in the <head></head>, it needs to be wrapped in $(document).ready().
$(document).ready(function(){
$("#someelement").click(function(){
alert("click");
});
});
alert is a method defined on the window object, such as, window.alert. It expects one parameter that is a string, and it must be a member of the window object. placing ("string") after alert, such as alert("string") will execute that function, resulting in the popup window with "string". The same thing happens when you place alert("string") as a parameter to a function, a popup window happens when said code runs.
Try this:
$(document).ready(function() {
$("#someelement").click(function(){alert("click")});
});
Here is a working Fiddle
I have a page with boxes and I want a function to run on each box click. Additionally, I want the function to run ONCE on page load.
(The idea is that the function "updates the state", and I want to update on each click, but also on page load - to initialize the state, so to speak.)
Normally, I do this like so:
$('.box').click(function() {
// do something
}).first().click();
So I attach the handler to each .box click event, and then I get the first .box element and trigger the click event on it.
This approach works, but it feels kind-of clumsy. How do you tackle this problem?
jQuery has triggerHandler()(docs), which offers a number of advantages that may be desired for your code.
$('.box').click(function() {
// do something
}).triggerHandler('click');
From the docs:
The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.
Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined
function hello() {
//Here goes your update function
alert('world');
}
$('.box').click(hello);
hello();
This is how I would probably do it.
(function(){
var foo = function(){
// stuff
}
$('.box').click(foo);
foo();
})();
Calls foo when it initializes and adds it to the click.
Something like this could also work :
$(document).ready(function($) {
$('.box').click(function() {
$(this).val("Value"); //Your function here
});
$('.box').each(function() {
$(this).val("Ready"); //Your function here
});
});
Demo