jQuery simple button bind - javascript

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');
});
});

Related

JQuery function .load not working

I have the next code. What am trying to do is when i refresh or open the page, to add the class intro. But my main problem is in the part :
$("body").load(function(){
I want when the page is opened, then to add the class .intro. Instead of body, i have also tried html, and still doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").load(function(){
$("p").addClass("intro");
});
});
</script>
<style>
.intro {
background-color:green;
}
</style>
</head>
<body>
<img src="https://k32.kn3.net/taringa/1/9/3/9/4/7/32/johnny_te_toco/330x330_248.gif" width="304" height="236">
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body>
</html>
You should not use load() for this purpose.
load() function description : Load data from the server and place the returned HTML into the matched element.
You need just ready function to achieve that :
$(document).ready(function(){
$("p").addClass("intro");
});
//OR
jQuery(function($){
$("p").addClass("intro");
});
Hope this helps.
Try this instead:
$(document).ready(function(){
$(window).load(function(){
$("p").addClass("intro");
});
});
Load event attached to the window. If that is what you meant? Load on a DOM element like that doesn't make much sense.
Whilst this should work, you could pull it out of your ready() event.
$(document).ready(function(){
// Nothing to see here...
});
$(window).load(function(){
$("p").addClass("intro");
});
This waits for the load of the window, but if you just want to add the class as soon as possible when the DOM is ready, well, you won't need the load() at all:
$(document).ready(function(){
$("p").addClass("intro");
});
Bonus: You should use on() to attach all events going forward.
$(window).on('load', function(){
$("p").addClass("intro");
});
on() is the preferred method for events in future jQuery versions, as older methods are deprecated.
All the best.
Put your code inside $(document).ready callback.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").addClass("intro");
});
</script>
<style>
.intro {
background-color:green;
}
</style>
</head>
<body>
<img src="https://k32.kn3.net/taringa/1/9/3/9/4/7/32/johnny_te_toco/330x330_248.gif" width="304" height="236">
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body>
</html>
$(window).on('load', function(){
$("p").addClass("intro");
});

How do you get javascript/jquery to work?

EDIT: Thanks for the suggestions everyone. I've gotten it squared away thanks to your help!
I am doing javascript/jquery tutorials on codeschool/codeacademy and everything seems to go fine there. But when I try to do something myself, I cannot get the javascript to actually trigger. I tried chrome and firefox. I disabled all plugin extentions. Must be a simple problem, please help!
The following code I cut and pasted from jquery (http://learn.jquery.com/about-jquery/how-jquery-works/)
Here is a link to the jsfiddle: http://jsfiddle.net/interestinall/n5mqryrj/
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
jQuery
<script src="jquery.js"></script>
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>
It does not work for me. Can someone explain why and tell me how to get it working? Thanks so much!
Theres nothing wrong with your code. We were all started somewhere and some of these suggestions are misleading
If you're not already aware, jQuery is a comprehensive library which makes complex javascript development simpler. Its important to note that everything you do with jQuery can be achieved using native javascript its just a little tricker and jquery handles all the complexities to work across a wide range of browsers. That is to say some things work in some browsers, where as others do things in a different way (notably IE).
To use jQuery on your website, you need to include it on your page. Its self executing and one way you can tell if its worked is running something like:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.1.min.js" ></script>
<script>
console.log($)
</script>
</body>
</html>
If you open the console in chrome (hit f12) you should see:
function (a,b){return new m.fn.init(a,b)}
Note that I'm using src="https://code.jquery.com/jquery-1.11.1.min.js" for the source of the script. You can use src="jquery.js" as per your script, but it means you need to save the contents of https://code.jquery.com/jquery-1.11.1.min.js to a file called jquery.js at the same level as your index.html (or the wherever-you-saved-your-code.html)
Ive noted some suggestions say you should include jQuery in the tag and, though this would work, its considered best practice to keep scripts at the bottom of the page for reasons I wont go into here.
As such, this should work for you (irregardless of browser extensions):
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
jQuery
<script src="https://code.jquery.com/jquery-1.11.1.min.js" ></script>
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>
Good luck.
You did not include jquery in your project.
change this line
<script src="jquery.js"></script>
to this line
<script src="https://code.jquery.com/jquery-1.11.1.min.js" ></script>
or any other version in
https://code.jquery.com/
You've used the wrong URL to jquery. http://fiddle.jshell.net/_display/jquery.js gives a 404 error.
Try using an absolute URI or picking the library from the Frameworks & Extensions menu.
You haven't included your jQuery properly. Try this instead:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
jQuery
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>
Try to replace
jQuery
with
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or download the jQuery-Scriptfile from jQuery.com, store it locally and use that one.
Here is a working example
http://jsbin.com/pajecubute/1/edit
jQuery
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
Updated your fiddle. You need not include JQuery separately in your HTML. It is already present for your selection on the left hand side. Your code works now.
http://jsfiddle.net/n5mqryrj/8/
Added ready function in the script section:
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});

jQuery preventDefault() issue

My problem is that there is no way to make preventDefault() work.
Here is my code:
HTML:
<a class="list-ui-controlcol-link list-ui-controlcol-link-delete" href="http://localhost/lmvc_trunk/pages/delete/17">Törlés</a>
JQUERY:
$(".list-ui-controlcol-link-delete").click(function(event){
event.preventDefault();
});
Even if I copy-paste the original example from jQuery's own site (http://api.jquery.com/event.preventdefault/) it is not working.
Could you explain me why this happening and how to make preventDefault work correctly?
You need to make sure that your script is executed after the DOM is loaded:
$(document).ready(function() {
$(".list-ui-controlcol-link-delete").click(function(event){
event.preventDefault();
});
});
See this page for more details: http://api.jquery.com/ready/
Where do you include your script? If you include the script in HEAD when the script loads there's no a.list-ui-controlcol-link-delete is present in the DOM.
Try doing this:
<html>
<head>
<title>test</title>
</head>
<body>
Torles
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Where app.js contains:
$('.list-ui-controlcol-link-delete').click(function(e) { e.preventDefault(); });
Although I'd recommend using the .on() function as it will dinamically bind the events on newly generated DOM elements:
$(document).on('click','.list-ui-controlcol-link-delete',function(e) { e.preventDefault(); });

Jquery .load not working with PHP page

I am currently working on a chat system experiment, and have run into an issue.
This is my code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getUpdates() {
$('#updates').load('chatlister.php', function() {window.alert('Load was performed.');});
}
setTimeout(getUpdates(), 1000);
</script>
</head>
<body>
<p>The updates are:</p>
<div id="updates"></div>
</body>
For some reason, the jQuery .load() function is not loading anything into the "updates" <div> section of the page. I checked chatlister.php and made sure that it had output, and I also made sure that the two files are in the same directory. I am very new to jQuery, so please bear with me. What did I miss?
You need to wrap your code in this
$(document).ready(function(){
// Code here
});
Because the code is never being executed, either that, or your php is wrong.
You should have a look at jQuery AJAX
You have to wait for the DOM to be created so run only after the document is ready:
$(document).ready(function(){
$('#updates').load('chatlister.php', function() {window.alert('Load was performed.');});
});
If you want to run it every seconds:
$(document).ready(function(){
var getUpdates = function() {
$('#updates').load('chatlister.php', function() {window.alert('Load was performed.');});
}
setInterval(getUpdates, 1000);
});

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');
});
});

Categories

Resources