Why does this "simple" `load` function not "work"? - javascript

sample:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#test').load(function(){
alert(1);
});
});
</script>
<TITLE> test load </TITLE>
</head>
<body>
<div id="test">
TEST
</div>
</BODY>

$(window).load(function () { ... });
Load events only fire on elements that have a URL associated with them, like images. You can however bind to the window load event which fires when all the elements on a page have loaded.
Alternatively you can bind to the document.ready event handler that fires when the DOM is ready to be manipulated. In jQuery we do this like so:
$(function () {
//run code here
});
Update
If you add elements to the DOM, do work on them before doing so:
$('#button').on('click', function () {
$('body').append($('<div />').addClass('some-class').text('Some Text').on('click', function () { alert('Ouch! You poked me.'); }));
});
Notice I ran some jQuery functions on an element I created using jQuery before appending it to the DOM.

.load is used as an ajax function in essence. you are trying to use it like a DOM load event.

Related

jQuery simple button bind

I'm new to jQuery, so this should be a simple question.
As far as I understand, I can bind a method to listen to an event, such as the click of a button, using
$('#buttonID').bind('click', function (){//some code});
However, this isn't working for me, so I must be doing something wrong.
This is my simple html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
<script src='test.js'></script>
</head>
<body>
<input id="SignIn" type="button" value="Sign In"></input>
</body>
</html>
Apart from loading jQuery files, it loads file test.js, which looks like this:
// JavaScript Document
$('#SignIn').bind('click', function() {alert('hi');});
Is that not enough for binding? I was hoping this would fire an alert dialog, but it doesn't, it seems the callback is not executed at all.
What is wrong here? Both files (html and js) are located in the same directory, and Google Chrome does not complain about anything in the JavaScript console, so from that end, everything should be fine.
Thanks for all help!
Wrap your code in document ready handler. It accepts a function which executes when DOM is fully loaded.
As you are using jQuery 1.3
$(document).ready(function() {
$('#SignIn').bind('click', function() {
alert('hi');
});
});
For jQuery 1.7+,
$(document).ready(function() {
$('#SignIn').on('click', function() {
alert('hi');
});
});
Additionally, As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
$(function(){
$('#SignIn').bind('click', function() {alert('hi');});
})
Try
$(function(){
$('#SignIn').click(function() {alert('hi');});
});
Move your Javascript to the bottom of the HTML page, right above the closing body tag.
That way the DOM is ready when it is loaded, and there's no need for $(document).ready() calls.
https://developer.yahoo.com/performance/rules.html#js_bottom
You may want to include your JavaScript files at the very bottom, and everything should work as expected. It is recommended to do this and to include CSS files at the top (head tag). For more information see link included by #Grim...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input id="SignIn" type="button" value="Sign In"></input>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
<script src='test.js'></script>
</body>
</html>
$( "#target" ).click(function() {
//Write some code here
});
You can try this.
$(document).ready(function(){
$('#SignIn').on('click', function() {alert('hi');});
});
You can use this.
$(document).ready(function () {
$("#SignIn").click(function () {
alert('demo');
});
});

Custom Jquery Not Available At Runtime With Dynamicallly Added Html

I have a page that looks like this..
<!DOCTYPE html>
<html>
<head>
<title>JQM</title>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.css">
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.js"></script>
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
</div>
<div data-role="content">
</div>
</div>
</body>
</html>
I am adding html in dymanically from the server in the content area. The problem is that when I add the content dynamically, the jquery function that I created statically on the page doesnt engage..
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
If I add the html statically all the code works fine and everything is good. My question is how do I make this jquery available to run once html is added to the page from the server?
I DID THIS AND IT WORKED, is there a more elegant way using .on or is this fine?
//got html blob
deferred.success(function (res) {
$(function () {
$('[data-role="list-divider"]').toggle(function () {
$('.' + $(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
}, function () {
$('.' + $(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
});
Since the jquery is currently ran when the document is ready and your content is not loaded yet it won't find the elements and wire-up the events. Adding your script to the ajax.success should solve your problem.
looking at your code, I don't see where you're loading the content dynamically. But if you want that script to run. You should try a document.ready() in front of that script
You can't bind event handlers to elements that haven't been created. Check out this:
http://api.jquery.com/on/
Try this:
$(function(){
$(document).on('toggle', '[data-role="list-divider"]', function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
Haven't tested it though. For on('click') this usually works.
What you do is you bind the 'toggle' trigger to the whole document ( $(document) ) and then check on what element is was triggered. This way you can detect elements that were created after the initialization of the DOM.
You have to use jquery .On() method to attach even handlers to contents dynamically added to pages. Check this - .on
Some thing lik this might work (didn't test) :-
$(function(){
$('[data-role="list-divider"]').on('toggle' ,function(event){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(event){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});

jQuery, getting "500 Internal Server Error" when running a jQuery statement

Whenever the jQuery is triggered I recieve the error 500 Internal Server Error, does anyone have any ideas why the code below might be causing this?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="../meta/js/jquery-1.7.2.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(e){
e.preventDefault();
alert('I clicked it');
});
});
</script>
</head>
<body>
<form name="form1" method="post">
<button id="button">grab user data</button>
<select></select>
</form>
</body>
</html>
I'm gonna guess its because of this variable:
<%=button.ClientID %>
There is nothing else (shown) that would signify anything else that would throw an error.
Can you clarify what you mean by 'jQuery is triggered'? Does that mean upon 'click' ?
Or just by loading this page (I assumed the later)
I would guess that it's giving the error with this line:
$('#<%=button.ClientID %>')
Hard code a value instead and test it:
$('#buttonID')
In order to achieve what you want this will do the job:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#myButton').on('click',function(){
alert("i clicked it");
});
});
</script>
</head>
<body>
<button id="myButton">Click Me!</button>
</body>
</html>
$(document).ready is used to execute your code just after your page is rendered, then $('myButton') will get any element with an id "myButton", then you will use the method "on" to attach any event you want, in this case you will want to choose the "click" event, then you should give an anonymous function where you will put the code you would like to execute on that action.
Your button is inside a tag with action="". This will cause a postback to "/". If your server doesn't handle this correctly, you will get an internal server error.
if you only want the alert to show, you can call preventDefault on the jQuery event object. Se example below:
$(document).ready(function() {
$('#<%=button.ClientID %>').click( function(e) {
e.preventDefault();
alert("i clicked it");
});
});
EDIT:
Forget what i wrote above. It doesn't work. Instead, use the submit event on the form. Like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="#{'/public/javascripts/jquery-1.6.4.min.js'}" type="text/javascript" charset="${_response_encoding}"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(e){
e.preventDefault();
alert('I clicked it');
});
});
</script>
</head>
<body>
<form id="form1" method="post" action="">
<button id="button">grab user data</button>
<select></select>
</form>
</body>
</html>
you are attaching the submit event to #form1 but your form doesn't have an id, only a name. You must select the form by name, $("form[name='form1']") or give it an id of id="form1".

Show javascript alert and do other actions?

Here's my code and nothing is happening:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git.js"></script>
<script>
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
</script>
</head>
<body>
<div class="clickMe">Click Me!</div>
</body>
</html>
However, nothing happens when you click the "clickMe" div.
Thanks!
Let the document be ready
$(function(){
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
})
The way you had it, the div is not yet available (the DOM is not loaded) so, no click handler is added. You need to wait for document to be available. The .ready() is to be used for that.
$(document).ready(function() {...})
$(function() {...}) - Shortcut
Try wrapping the jQuery code inside this:
$(document).ready(function() {
// Handler for .ready() called.
});
When you execute the existing code in the head, the clickMe div does not exist.
Try this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
});
</script>
</head>
<body>
<div class="clickMe">Click Me!</div>
</body>
</html>
You by comparing the differences you will find out the solution. Basically is this line: $(document).ready(function(){});
The DOM is not loaded yet when your JavaScript code is executed. You have to add the code to the .ready() callback. Then the code is executed when the browser parsed the HTML and jQuery can find the elements:
$(function() {
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
});
$(function(){..}); is shorthand for $(document).ready(function(){...}).
DEMO
The script is running before the .clickMe element even exists. Wrap your code in a dom ready callback:
$(function() {
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
});
Another solution would be moving your script below the element definition but using the dom ready event is much cleaner.
The issue is that you are attaching the event handler before the element is rendered to the DOM. Try this instead:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git.js"></script>
<script>
$(document).ready(function() {
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
});
</script>
</head>
<body>
<div class="clickMe">Click Me!</div>
</body>
</html>
The code passed into the $(document).ready function will be executed once the page is entirely loaded - so you can safely attach events to yet-to-be-created elements.
http://api.jquery.com/ready/
You're asking jquery to find your clickMe div before it exists. It's down lower on the page and the browser has not loaded it yet. A simple fix is to set up your click handler during the document ready event:
<script>
$(document).ready(function() {
$(".clickMe").click(function() {
alert('hi!');
// Do other stuff
});
});
</script>

jQuery and js file not loading?

I need to dynamically update the contents for every few seconds, without reloading the page, so i thought to use jquery load() function, this loads the contents fine but not the js or jquery file from head tag.
Here is sample code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{$PAGE_TITLE}</title>
<link rel="stylesheet" type="text/css" href="../web/css/style.css" />
<script type="text/javascript" src="../web/js/jquery-1.3.2.min.js" ></script>
<script type="text/javascript" src="../web/js/wz_tooltip.js"></script>
<script type="text/javascript" src="../web/js/tip_centerwindow.js"></script>
<script type="text/javascript" src="../web/js/tip_balloon.js"></script>
<script type="text/javascript">
{literal}
$(document).ready(function() {
setInterval(function(){
$("#content").load("load_contents.php");
},20000);
......
});
{/literal}
</script>
</head>
<body>
<div class="content">
</div>
</body>
</html>
Suggest me the solution...
Updated: Tooltip js is not loading, y?...
I can't find the reference, but any javascript in the page that is loaded will automatically be disabled to prevent conflicts. If you need to do something to the loaded content, I would suggest using either live() or delegate() on the main page to act on the loaded content.
I agree with fudgey about using live (delegate isn't an option in 1.3.2) if possible. If your plugin doesn't support that though (which I'm guessing it doesn't since it's not working), you can pass a function to .load that will run when the content is loaded. Here you will want to hook up these new elements to your plugin. For example, so for instance say you wanted to use draggable from jQuery UI on all divs inside content , you might do
$(document).ready(function() {
var init = function(){
$("#content div").draggable();
};
init();
setInterval(function(){
$("#content").load("load_contents.php", init)
},20000);
});
If you do this with your tooltip plugin and whatever else, you are reloading into content, it should work. Be careful to call the init method only on content within #content so you don't end up adding tooltips twice to other areas. Using a plugin that uses delegate (upgrade to latest jQuery) or live will avoid having to do the selection and rebind each time you add elements, making for faster reloads.

Categories

Resources