JavaScript Pop up : Invoking in JQuery - javascript

In my application I am using a simple JavaScript popup and successfully invoking it this way-
<a href="javascript:popup('Hello World')>Click Me</a>
I was wondering whether it is possible to invoke the same popup on other jQuery events. For instance
$("#some_button_id").click( function() {
javascript:popup('Hello World');
});
The above method doesn't work. Any other solution?

EDIT - You don't need the javascript: part because you are not attaching javascript inline.
But that is not the cause of the error so make sure that you wait until the DOM is ready before attaching an event handler.
$(function(){
var popup = function(msg){
alert(msg);
}
$("#some_button_id").click( function() {
popup('Hello World');
});
});
and of course make sure you define popup() somewhere

If the popup function is defined on your page then you should use
$("#some_button_id").click( function() {
popup('Hello World');
});
The javascript: prefix is only needed when you use javascript code directly inside your html attributes.

$("#some_button_id").click( function() {
popup('Hello World');
});
should work.
EDIT
this will work for sure if the id exit when the event if fired , wether or not it has been created when the the listener was added , it is called delegation :
$(document.body).click( function(e) {
if(e.target.getAttribute("id")=="some_button_id"){
popup('Hello World');
}
});

Related

jQuery bind event not firing on elements loaded via $().load()

I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
$("#contentDiv").load("some.html")
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
}
});
The event will not fire. If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work? I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff. It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is. But, thanks for pointing it out.
EDIT2: Grrrrrrr. });
load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
$("#contentDiv").load("some.html", function(){
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
});
});
});
Hope it helps :)
one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();
and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )
If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
alert("Here I am!");
});
jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
//you should put here your event handler
});
});
Your issue is that jquery load() function is asynchronous as #lucas mention. But his code has syntax errors, try this:
$(document).ready(function () {
$("#contentDiv").load("some.html", function () {
$("#saveButton").click(function () {
alert("Here I am!");
});
});
});
Hope it helps now
You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
$("#saveButton").on('click',function() {
alert("Here I am! Bound in callback");
});
});
});
OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
alert("Here I am! bound to container div");
});
EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
$("#saveButton").on('click',function() {
$("#contentDiv").load("some.html", function() {
alert("Here I am! Bound in callback");
});
});
});

onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})

Bind click to images loaded via AJAX

I've been having some trouble with this block of code, and I think I've finally narrowed the problem down. Here's the jQuery function...
$(document).ready(function(e) {
$('#formattingSection').load ('formattingdoc.html #formatting');
$('#loadFormatting').click(function() {
$('#formattingSection').load ('formattingdoc.html #formatting');
});
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys');
});
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
Basically, it works like this. The page loads, we load part of a doc via AJAX. There are four buttons on the page, each one loads a new section via AJAX. When you click #loadSmileys, it will load via AJAX several images and display them in the DIV.
I'm binding a click() event to those images... but what I've found is that since the images aren't on the page at load time, the click event never gets bound. When I strip all the code away and load the images without AJAX, the click binds okay.
So... my question here... is there a way to bind the click event to the images AFTER they are loaded via AJAX?
For reference... I did make a jsBin HERE, but it's basically just hard coding the images to that I can see it works without the AJAX stuff going on.
Try:
$("#formattingSection").on("click","div img",function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
As $.on attaches event handler to the parent and all events from children are delegated to the parent
Documentation
Yes, you totally can attach event handles to DOM nodes loaded on-the-fly. The trick is to use jQuery.get instead of .load. .get allows you to add an additional callback function that gets executed upon AJAX completion - the perfect place for you to add your $("#formattingSection div img") code. Here's what it would look like:
$('#loadSmileys').click(function() {
$('#formattingSection').get ({
url: "formattingdoc.html",
success: success
});
});
function success() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
$('#formattingSection').load ('formattingdoc.html #formatting', function( response, status, xhr ) {
loading_completed();
});
function loading_completed()
{
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
Try this
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys', function() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
});
You should use the 'on' method. This can apply click handlers to elements created after the on method is called.
e.g.
$("#formattingSection").on("click","div img",function() {
...
}
As imges are added, they will automatically get the click handler functionality.
This question I asked helps explain the difference: jquery use of bind vs on click

jquery that just waits

I normally set up my javascript code to have a function. But due to the fact that the application generates most of the HTML and javascript calls from a VB6 application I would like to create a jQuery function that is more like a listener. So for example if I have a td tag that has the class 'gridheader1' I would like the jQuery to wait for it to be clicked.
I'm assuming that I would use the bind... But I'm getting javascript errors with it... If you can offer suggestions on where my code is wrong that would be great.
$('.gridheader1').bind('click', function()
{
alert('hi I got clicked');
});
Again this just has to sit out there on the main .js file. It isn't attached to any functions. Please let me know.
Thanks
you want
$('.gridheader1').bind('click', function(){
alert('hi I got clicked');
});
note the dot at the start of selector - it means class
// static tags
$(function(){ // DOM ready
$('.gridheader1').click(function()
{
alert('gridheader1 clicked');
});
});
// or if the tag is loaded via ajax use 'live'...
$(function(){ // DOM Ready
$('.gridheader1').live('click', function()
{
alert('gridheader1 clicked');
});
});
// or if you already have a function defined that you want to call, you can pass in the function instead of using an anonymous function.
function alertAboutStuff(){
alert('gridheader1 clicked');
}
$(function(){
$('.gridheader1').click(alertAboutStuff);
// $('.gridheader1').live('click', alertAboutStuff); // for tags loaded via ajax
});

unload event when using master page

In my project i have used master page.In one particular page , i want a function to be executed on page unload(javascript event) event of that particular page.To achieve this i have written
$('body').bind('unload',function()
{
alert('hello');
} );
But this is not working.This function is not getting called when i move to other page.
How should i achieve this.
Well, I suppose its a problem when writing the question but your code should be:
$(window).bind('unload',function()
{
alert('hello');
});
You are missing the ending ); and the event should be bound to the window...
[Edit: Added the bind to the window instead of 'body']
$(window).bind("unload", function(){
alert(123);
});
worked for me :)
$(document).ready(function(){
$(window).unload( function () {
alert("Bye now!");
} );
});
try this. the document.ready function runs on pageload. so your bind will execute and is should work.

Categories