I have the most simple .on function i could write. it started off as trying to validate a form on load, then after many minutes of frustration I tried the following:
$('p').on('load',function(){
console.log("hello");
});
This doesn't even work. I'm baffled. Ive tried it both IN and outside of $(document).ready(), neither work, and ive also checked console, there are no errors with my JS.
What could be causing this, its making me so mad
demo
You can always check for existence using length:
var par = $('p.paragraph'); // make it special with some ID or class
if(par.length){ // If your elements exists....
alert(" I'm 'LOADED!' ;) ");
}
ps, divs and other elements don't have a load-event - thats only available on images, windows, frames and iframes.
jQuery does not have a way of firing an event the first time a particular element becomes available. You can do it with setInterval, however there are usually much better ways to handle it depending in the situation.
setInterval(function(){
$("p").not(".alreadyloaded").trigger("load").addClass("alreadyloaded");
},100);
$(document).on('load','p',function(){
console.log("hello");
});
I do not suggest using this method if at all possible.
A better way of handling it would be to either use the callback of the event that is adding the p element (such as the success of the .load() or $.ajax) or by binding delegated events, such as $(document).on('click','p',function(){ alert('hello'); });
Related
Is it possible to have multiple click events for the same element? I have tried to simply have it like so:
$('#templates').click(function(e) {
do something..
});
$('#templates').click(function(e) {
do something else also..
});
Yet only the second event fires. I cannot find any decent answers explaining how to do this for a singular element in an on-click?
Note: the first click event calls server-side and loads a new PHP template (this may have an effect on what I can use in the second call I guess, as individually both clicks work but the server call does not work if I try a second click for the same element)
$('#templates').click(function(e) {
functionOne();
functionTwo();
});
function functionOne(){
}
function functionTwo(){
}
perhaps?
Please check this fiddle:
http://jsfiddle.net/DqSSd/
As you can see it should work well.
So please provide more information, and it would be better, if you provide JS fiddle as well.
Because so far the problem might be in:
second event is fired before first event returns the result
first event returns error from the server
some of events contains syntax error
etc
You may check something of those with investigation of NET calls to server (with Firebug or Chrome Developer toolbar).
Also for testing purposes you can type in console $('#templates').data("events"), so you will be able to see all events and handlers for particular element.
I have a problem that happens only on a specific computer(FFX 3.6.13,Windows 7,jQuery 1.4.3).
Sometimes document.ready is fired but when trying to get elements to attach the event handlers,the elements don't exist!
the code goes something like this:
$(function(){
window.initStart = true;
$("#id_of_element").click(function()...);
window.initEnd = $("#id_of_element");
});
the window.initStart/End are there for debugging,sometimes this code runs just fine,but sometimes window.initEnd is just a empty jQuery set(length == 0).
What this means is that document.ready is always fired,but sometimes it is fired before elements are available.
Does anybody had this problem? what could the problem be?
One way that you could try to get around this would be with using .live instead of .click. The following code
$('#idOfDiv').live('click', function() { doStuff(); });
will attach the input function to the click event of everything that is dropped on the page with an id of 'idOfDiv' as soon as it makes it to the page. Whereas .click executes immediately, this should be attached no matter what time the divs make it to the page.
Cheers
There's an article on SitePoint that demonstrates how to sense when certain dom elements are available.
Also I know this is a version specific issue, but if you were on Jquery 1.5 the deferred objects stuff would be useful here.
It seems that this code:
$(function(){
$('.show_hide_login').toggle(
function (){
alert('show');
$("div#fullpage").show();
$("div#loginbox").show();
},
function (){
alert('hide');
$("div#loginbox").hide();
$("div#fullpage").hide();
}
); });
Any idea on why it would be running twice when I click on either link (two, one is a div and one is an anchor)?
How many elements do you have with the .show_hide_login class? I'll guess you have two of those. In which case, $('.show_hide_login') result contains two elements, and toggle() is executed for each of them.
This isn't an answer to your question, but you could clean up your code a bit like so:
$(function() {
$('.show_hide_login').toggle(
function() {
alert('show');
$("#loginbox,#fullpage").show();
}, function() {
alert('hide');
$("#loginbox,#fullpage").hide();
});
});
As to your actual problem, I suspect Nick's guessed the culprit. Check out this demo to see the result of binding the same event twice: http://jsfiddle.net/9jPLv/
In addition to adding an alert prior to the binding of the toggle event, you could add in an unbind() and see if that solves the problem, like so:
$('.show_hide_login').unbind().toggle(
If that solves it, the toggle binding is definitely being run twice, so you'd just have to figure out why.
my answer is just a kind of checkpoint,i had the same issue but for different reason. I did include the script file in base page as well as child page. this resulted in toggle running twice if you have this problem check that the script is added only once.
It might be the same issue i was having.
so if you got an element with a script tag in it - then you move that containing element or wrap it with another tag in jquery - then the ready function in jquery is executed again - thus binding a second toggle function to your element.
as suggested $('.show_hide_login').unbind().toggle( is a workaround that does work, but better to try moving your javascript code to the head or bottom of the page.
I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.
I am using this css tricks code snippet to refresh that part of the page:
$('#refreshbutton').click(function() {
var url = "http://myUrl.com/indexTest.php?ID=" + Math.random();
setTimeout(function() {
$("#maindisplay").load(url+" #maindisplay>*","");
}, 100);
});
The problem is that the elements within #maindisplay are changed, thus are considered new elements in the dom. Since the scripts that select those elements and attach functions to them run at domready and not during the partial refresh, this poses a problem.
So far I have been unable to find a way to reattach the scripts to the elements within #maindisplay after I partially refresh it.
My question is: What is the optimal way to reattach the scripts to the refreshed area of the page.
Thank you for any advice.
You need to use the live() function to attach your click handler.
You have the following options that I can think of:
Put the attach in a function and call that function on page refresh
Use the .live() functionality
Use .delegate() functionality
Put the Javascript reference to the functionality in a reference in the refresh so that it executes as a part of that refresh
Put the function in the callback
make it part of your setTimeout
some other creative method I did not think of...
Just a note: I would look at the .delegate() with contextual selection added in recent versions (available in 1.4.2 for instance).
Does load() not take a callback function as it's second argument? Why not reattach event handlers to the elements with that function?
$('#result').load('ajax/test.html', function() {
//reattach event handlers here.
});
I have been trying to add onclick event to new elements I added with JavaScript.
The problem is when I check document.body.innerHTML I can actually see the onclick=alert('blah') is added to the new element.
But when I click that element I don't see the alert box is working. In fact anything related to JavaScript is not working..
here is what I use to add new element:
function add_img() {
var elemm = document.createElement('rvml:image');
elemm.src = 'blah.png';
elemm.className = 'rvml';
elemm.onclick = "alert('blah')";
document.body.appendChild(elemm);
elemm.id = "gogo";
elemm.style.position='absolute';
elemm.style.width=55;
elemm.style.height=55;
elemm.style.top=200;
elemm.style.left=300;
elemm.style.rotation=200;
}
Here is how I call this function:
<button onclick=add_img()>add image</button>
Now the image draws perfectly inside the browser. But when I click the image I don't get that alert.
.onclick should be set to a function instead of a string. Try
elemm.onclick = function() { alert('blah'); };
instead.
You can also set attribute:
elem.setAttribute("onclick","alert('blah');");
Not sure but try :
elemm.addEventListener('click', function(){ alert('blah');}, false);
you can't assign an event by string. Use that:
elemm.onclick = function(){ alert('blah'); };
Short answer: you want to set the handler to a function:
elemm.onclick = function() { alert('blah'); };
Slightly longer answer: you'll have to write a few more lines of code to get that to work consistently across browsers.
The fact is that even the sligthly-longer-code that might solve that particular problem across a set of common browsers will still come with problems of its own. So if you don't care about cross-browser support, go with the totally short one. If you care about it and absolutely only want to get this one single thing working, go with a combination of addEventListener and attachEvent. If you want to be able to extensively create objects and add and remove event listeners throughout your code, and want that to work across browsers, you definitely want to delegate that responsibility to a library such as jQuery.
I don't think you can do that this way. You should use :
void addEventListener(
in DOMString type,
in EventListener listener,
in boolean useCapture
);
Documentation right here.
cant say why, but the es5/6 syntax doesnt work
elem.onclick = (ev) => {console.log(this);} not working
elem.onclick = function(ev) {console.log(this);} working
You have three different problems. First of all, values in HTML tags should be quoted! Not doing this can confuse the browser, and may cause some troubles (although it is likely not the case here). Second, you should actually assign a function to the onclick variable, as someone else meantioned. Not only is this the proper way to do it going forward, but it makes things much simpler if you are trying to use local variables in the onclick function. Finally, you can try either addEventListener or jQuery, jQuery has the advantage of a nicer interface.
Oh, and make sure your HTML validates! That could be an issue.
JQuery:
elemm.attr("onclick", "yourFunction(this)");
or:
elemm.attr("onclick", "alert('Hi!')");