I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.
Related
I'm attempting to use html onload event to trigger javascript, but is not working. The original code was:
html:
<div id='map' onload="generateMap.createMap();"></div>
JS:
var generateMap = function(){
return{
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
}
In an attempt to test, I changed the html to:
<div id='map' onload="alert('test');"></div>
Can anyone tell me why nothing is working?
First, the onload attribute is not valid for a div tag. You most likely intended to place the onload in the body tag.
Unfortunately, that's not the only problem.
In your onLoad you are referencing generateMap as if it is an object with method createMap. However, this is not the case. You have assigned generateMap to an anonymous function.
To get your code working, generateMap needs to be an object with method createMap.
You just need to set it as an object in the first place:
var generateMap = {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
Or if you need to retain the anonymous function for whatever reason, you can use an immediately executing function:
var generateMap = (function(){
return {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
})();
There is no onload event for a div. You can use the script tag just after the div tag to emulate onload behavior.
Use this
<head>
<meta charset="utf-8">
<script type="text/javascript">
var generateMap = {
createMap: function(element) {
navigator.geolocation.getCurrentPosition(initialize);
}
};
</script>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
generateMap.createMap('map');
</script>
</body>
Assuming Chrome.. div tags do not have an onload event. Check the following two jsfiddles:
Does not work:
http://jsfiddle.net/o81e4dkr/
Works:
http://jsfiddle.net/p3osqrdn/
I do not know of a way to have an event fired when a div is loaded, unless it is being loaded in via jQuery.load(), in which case you can use the callbacks.
If you're using jQuery then I like the following function which adds onload capability to all tags:
$(document).ready (function () {
jQuery.each ($("[onload]"), function (index, item) {
$(item).prop ("onload").call (item);
return false;
});
});
Is it possible to add a javascript event to a DOM element that already has a onclick event, but I want to keep that event property.
I have radio buttons like this:
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this);" />
in which I want to add
window.location.href=window.location.href
while keeping the original onclick, but I have no access to the html, I can only modify through javascript.
so my desired code will be
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this); window.location.href=window.location.href" />
Wrap the
window.location.href=window.location.href
in function, lets call it
onRadioButtonClick()
then, just do
var self = this; //keep the context of the file
$("[name=checkout-payment]").on('click', function () {
onRadioButtonClick.call(self); //call the method with the normal context.
//continue code..
});
You could try:
var curHandler = $('#checkout-payment-56').attr("onclick");
$('#checkout-payment-56')[0].onclick = null;
$('#checkout-payment-56').click(function () {
window.location.href=window.location.href;
});
I actually found out there was a much simpler way to acheive my desired result.
$( '.webshop-checkout input[type="radio"]' ).click(function() {
location.reload(true);
});
i am sorry i was not clear in my original post, and it has been edited.
If you want to add this to every .webshop-checkout input[type="radio"], you could do it that way:
$('.webshop-checkout input[type="radio"]').click(function(){
window.location.href=window.location.href;
});
JS Fiddle Demo
$("#checkout-payment-56" ).bind( "click", function(evt) {
console.log('that works');
//sessionStorage.setItem(evt.target.id,evt.target.className);
});
i'm trying to get the href value in multiple links or tag a.and i tried with this code
var val;
$(document).ready(function() {
$("a").click(function() {
window.val = $(this).attr("href");
alert(window.val);
});
it is working fine for the multiple links and which is inside the file that is local, here few demo links
a
b.....
but problem is i want that href value globally available because i'm using that in other file . My problem is how to make it global, or is there any other way to do it.
and how to write our own function to work the same thing without using $(document).ready function.
this whole thing in one html page but i want only href value in other html page , so if we write our own js function we can use this in both html pages . And that function should return href. but here i dono how to return to $(document).ready function.
You can create an object-based variable:
var screen = {
link:''
};
And then assign / access on click:
$('a').on('click',function(){
screen.link = this.href;
alert(screen.link);
});
I advocate this over assigning variables to the window ... a little more control this way.
Notice I used this.href instead of $(this).attr('href'). As the most interesting man in the world says, I don't always use vanilla JS, but when I do it's about 600,000 times faster.
EDIT So you want to get rid of $(document).ready() huh? Now you're venturing into the shark-infested waters of pure vanilla JS.
var screen = {
link:'',
assignLink:function(href){
screen.link = href;
alert(href);
}
},
links = document.getElementsByTagName('a');
if(window.addEventListener){
for(i = links.length; i--;){
links[i].addEventListener('click',function(){
screen.assignLink(this.href);
});
}
} else {
for(i - links.length; i--;){
links[i].attachEvent('onclick',function(){
screen.assignLink(this.href);
});
}
}
This is just winging it, so don't scathe me if it isn't flawless, its more to make a point. See why jQuery is so handy? All that extra crap is done in the background for you, so that you just need to deal with the burden of $(document).ready() and not have to deal with the rest of this kind of stuff.
EDIT AGAIN So ... you want to access this value across pages?
var screen = {
link:((localStorage['link'] !== null) ? localSorage['link'] : ''),
setLink:function(href){
screen.link = href;
localStorage['link'] = href;
alert(href);
},
getLink:function(){
return screen.link;
}
};
$('a').on('click',function(){
screen.setLink(this.href);
});
This use of localStorage is just an example ... you can get more elaborate or use cookies if you want IE7- to work, but this just providing ideas. You can set the value whenever you want using the screen.setLink function passing the href, or you can get the value whenever you want using the screen.getLink function.
Take a look at this example:
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery 1.9.1 Online</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var val;
$(document).ready(function() {
$("a").on('click', function() {
window.val = $(this).attr("href");
alert(window.val);
return false;
});
$("div").on('click', function() {
alert (val);
});
});
</script>
</head>
<body>
a
b
<div>click here</div>
</body>
</html>
Once you click either the link a or b val will be set. Clicking the div tag will alert you the current reference of val.
Declare val outside to make it global and you can use the val inside the function to set the href globally
var val;
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
val = $(this).attr("href");
alert(val);
});
});
jsfiddle
There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".
I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.