JQuery event handler executing on page load - javascript

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

Related

alert or log click function content

The following code:
alert(document.getElementById("div").click());
runs the click function. But I want to alert or log the content of such a function. What have i to do instead?
The click method is a DOM Level 2 method for <input> elements with type "button", "checkbox", "radio", "reset", or "submit" (see: DOM-Level-2-HTML: click method and HTMLElement.click() on MDN).
The click method (function) itself is implemented natively by the browser. It means that you can try to print its content with:
alert(document.getElementById("div").click);
(note no parentheses after click) but all you will get is:
function click() { [native code] }
which is probably not what you want.
Are you sure you don't want to get the source of click event handlers instead of a click method?
To print out the content of the function, you have to execute:
console.log(document.getElementById("div").click)
Then go to the console of Dev Tools, where you will find a reference to the source code of logged function, or just the source, if it's native browser's implementation.
console.log(''.toLocaleLowerCase)
toLocaleLowerCase() VM222:2
console.log($);
e(e, e) VM227:2
If I understand, you want to actually alert the source code of the click function, yes?
Just remove the parentheses, which are what tells javascript to run the function rather than reference the function:
alert(document.getElementById("div").click);

Understanding Javascript syntax?

I am wondering if anyone can help with understanding this Javascript syntax.
Lets say I have the following:
<script>
$(function(){
$("#contactbutton").click(function(event){
$("#dialog").dialog({width:500});
});
});
</script>
I understand that the first line is testing if the DOM is ready and loaded. It then passes control to the inside function.
This inside function gets the element with an ID of contactbutton and for the click event, passes control to the next function.
This inner function, gets the elemnt with an ID of dialog and calls the .dialog method to display the dialog box. However, I am not sure about:
function(event)
What is the event parameter here, and why do we need it? Also, can this be renamed to anything we want?
Thanks,
This is actually an object that is accessible within that function. Usually it is called the event reference. The object holds details, functions, variables, etc., about the function and event, allowing you to handle the event and access properties of it. You are able to access it once you set a name to the first argument of the handler, that is function(event) { }
In a certain case, say you wanted to prevent the default event of an anchor link which would be to navigate the page to stackoverflow.com. preventDefault is a function that can do this, that is, prevent the default event. In this case that would be to prevent the navigation to stackoverflow.com. You are able to access the preventDefault function using the syntax event.preventDefault() if you have assigned the name event to the first argument of the handler.
For another example, in an onkeydown event you can access which key has been pressed with event.keyCode.

Linking html element to jQuery.click() using attribute "title"

I have a html code:
<a title="intro">INTRO?</a>
I need to link a jQuery click event on the tag. Using the solution given here I wrote the following javascript:
jQuery("a[title='intro']").click(alert("abc"));
However the page is alerting ("abc") on page load rather than on clicking the tag. Also to inform that the above code is NOT inside the load function jQuery(function() {... } and is a separate function.
Any solutions pls?
You are invoking the alert function during the event registration and is passing the value returned by the alert as the click callback handler.
Instead you need to pass a function reference as the click callback and within the function you can add the alert call
jQuery("a[title='intro']").click(function(){
alert("a")
});

Why is this click event automatically triggered in jQuery?

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.)

Execute function on each item click, but also once on page load

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

Categories

Resources