I'm playing around with event-delegation from http://learn.jquery.com/events/event-delegation/
.I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="A small web app to manage todos">
<title>TO-DO jQuery Tests</title>
<!--src attribute in the <script> element must point to a copy of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "article" ).on( "click","a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href=\"#\"id='link-2'>Link 2</a> </article>" );
});
</script>
</head>
<body>
<div id="test-container">
<article>
Link 1
</article>
</div>
</body>
When I click on Link2 I get no output on the console? Why isn't the event-handling working?
You have to bind to the closest static parent.
This case test-container.
$( "#test-container" ).on( "click","article a", function() {
// your code
});
The problem is that the second link is added dynamically and the click binding happens before the second link exists. That's why it has no affect on it.
Your code should look like this (instead of $(document) you can also use any static parent container as Ricardo pointed out):
$(document).ready(function() {
$(document ).on( "click","article a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href=\"#\"id='link-2'>Link 2</a> </article>" );
});
Related
With the following piece of code:
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$j = JQuery.noConflict();
function test() {
$j("#li1").on(
"click",
function() {$j.ajax({
url : "user/create_user_view",
success : function(result) {
$j("#div1").html(result);
}
});
});
}//test()
$j(function(){
test();
});
</script>
</head>
<body>
<ul>
<li id="li1">li1</li>
<li id="li2">li2</li>
</ul>
<div id="div1">div1</div>
<div id="div2">div2</div>
</body>
</html>
Actually the result of ajax call is a html file which is indeed a form,
I want to register events to the added elements of .html file,
I know about $("parent-selector").on("event","child-selector",callback(){
// code here
});
How to register js events to elements added dynamically through ajax in div1?
Update:
My question is using $("parent-selector").on("event","child-selector",callback(){
// code here
});
will register events only to direct children of #div1 or its descendents too?
You can easyli attach eventhandlers to dynamic elements, you have to write it a little bit diffrent:
$('body').on('click', '.myDynamicElement', function(ev) {
// Do your stuff in here...
});
Take a look into this Demo, Cheers Jan
I am learning JQuery and facing some problem.
<html>
<head>
<link rel="stylesheet" href="css/puzzle.css" type="text/css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/test.js" type="text/javascript"></script>
</head>
<body>
<div id="parent">
link1
link2
link3
</div>
<body>
</html>
$(
function() {
$("#parent").on("click", "a", function() {
linkClick(this);
});
function linkClick(link) {
$("#parent a").first().off("click");
console.log(link);
}
}
)
Question1: When the user clicks one of the links, can I remove the link's event haneler?
Question2: If the Question1 has been soled, can I add the onclick event handler back to "the specified link" without affecting other links?
Thanks for your reading.
==
I tried to use $("#parent a").first().off("click"); to unbind the first link's event handler.
But no matter how many times I click the first link, this console still prints data.
How do I remove the link's event handler and then add it back in a few seconds???
Use off
Remove event:
$( "#parent a").first().off( "click" );
Add Event:
$( "#parent a").first().on( "click", function(){
//click event code
})
Use:
//Remove click event for first element
$( "#parent a").first().off("click");
//Bind new event to element:
$( "#parent a").first().bind('click',function(){
//click event code
})
I have a document called "info.html".
it have 5 pages:
food
toys
entertainment
smartphones
electronics
I want that once a page loads, jquery send a request to the server for information about this item.
I all need to know is how to trigger this function?
Tried:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>CoCouppn!</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script type="text/javascript">
$(document).on("pageshow", function() {
alert($(this).attr('id'));
});
</script>
</head>
<body>
<div data-role="page" class="pge" id="food">
food
</div>
<div data-role="page" class="pge" id="toys">
toys
</div>
<div data-role="page" class="pge" id="entertainment">
entertainment
</div>
<div data-role="page" class="pge" id="smartphones">
smartphones
</div>
<div data-role="page" clsas="pge" id="electronics">
electronics
</div>
</body>
</html>
It alerts "undifined" instead of page ID.
What is the problem?
Note that pageshow is deprecated in jQuery Mobile 1.4: http://api.jquerymobile.com/pageshow/
Note also that $.mobile.activePage is deprecated.
If you want to get the active page ID, you can do:
$.mobile.pageContainer.pagecontainer( 'getActivePage' ).attr( 'id' );
or
$('body').pagecontainer( 'getActivePage' ).attr( 'id' );
or
$(':mobile-pagecontainer').pagecontainer( 'getActivePage' ).attr( 'id' );
I do not personally recommend the latter two, as you are free to set a different pagecontainer, which in fact I do in Jasmine tests.
Note that the page must really be active first (it is not active yet in pagecreate, for instance).
pagechange event and retrieve page's id from data object.
$(document).on("pagechange", function (e, data) {
var page = data.toPage[0].id;
});
Demo
pageshow:
$(document).on("pageshow", function (e, data) {
var page = $(this)[0].activeElement.id;
});
Demo
You can get the current page information in a shorter and clearer way:
$(".ui-page-active").attr("id")
This is just a variation from the code shown here: http://demos.jquerymobile.com/1.4.5/toolbar-fixed-persistent/#&ui-state=dialog
Try $(document).ready( function ), $(document).ready allows you to execute a code in jQuery only when the page is loaded.
If you want to use pagecreate event, use this.id
$(document).on(
"pagecreate",
'#page_1, #page_2',
function(event) {
var pageId = this.id;
...
}
);
I am new to web-designing. I have this sample code which toggles a div when we click anywhere on the window.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slide demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style>
#toggle {
width: 100px;
height: 100px;
background: #ccc;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
</head>
<body>
<p>Click anywhere to toggle the box.</p>
<div id="toggle"></div>
<script>
$( document ).click(function() {
$( "#toggle" ).toggle( "slide" );
});
</script>
</body>
</html>
How can I add an image and change the image for show and hide? I have an '>' icon. When I click on it, div should appear and '>' should change to '<'
$('#buttonid').on('click', function () {
$('#toggle').toggle('slide');
});
add a button with an unique id like this
<button id="buttonid">click to toggle </button>
I think you can do as follow
<img src='source:<' id='imageid' data-othersource='source:>' />
You can declare an image like that with the two sources and then switch the src in jQuery.
//wait for the document to be fully loaded to execute
$(document).ready(function(){
//use event delegation
$(document).on('click','#imageid',function(){
var $this= $(this);
$('#toggle').toggle('slide',function(){
//swap src of the image on toggle is completed
var imgsrc = $this.attr('src');
$this.attr('src',$this.data('othersource'));
$this.data('othersource',imgsrc)
});
});
});
This way if for some reasons, you have to change the images, you don't need to get back to script, you just need to change the html.
http://jsfiddle.net/AmqcY/
Note: event delegation is not necessary in this case, but still i think it's important you read about that part for furthur use.
instead of registering the click handler to document, register it to a button
if you have a button with id mybutton then
//dom ready handler so that the script is executed after the dom is loaded
jQuery(function(){
//register the click handler to an element with id mybutton
$('#mybutton').click(function () {
$("#toggle").toggle("slide");
});
})
Demo: Fiddle
By id:-
<button id="button_id">click to toggle </button>
$('#button_id').click(function() {
$( "#toggle" ).toggle( "slide" );
});
By class:-
<button class="button_class">click to toggle </button>
$('.button_class').click(function() {
$( "#toggle" ).toggle( "slide" );
});
Try like this
$('#yourbuttonId').click(function () {
$("#toggle").toggle("slide");
});
Demo
Try this Code
$('body').on('click',function(){
$('#toggle').toggle('slide');
});
jQuery is doing something strange for me: it just doesn't work and hides the div only for split a second. What am I doing wrong?
The code in question, as simple as can be.
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Experiment</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<script>
function doHiding() {
$("div.thread").each(function() {
$(this).hide();
});
}
</script>
Hide
<div class="thread">I like trains.</div>
</body>
</html>
I am using Chromium on Linux. I see the div dissapear for split a second, but it appears again immediately.
function doHiding() {
$("div.thread").each(function() {
$(this).hide();
});
return false;
}
it is not hiding again it is the page that is being refreshed because href="" links to same page
NB: i guess you used onClick="doHiding()" for the sake of demo only (otherwise handle your event within jquery scope)
You could try changing
<a href="" onClick="doHiding()">
into
<a href="#" onClick="doHiding()">
See: http://jsfiddle.net/aVNuf/
You can try the click event in jquery instead doing it inline.
http://jsbin.com/iseref/1/edit
html:
Hide
<div class="thread">I like trains.</div>
jQuery:
$(function(){
$('a').on('click', function(e){
e.preventDefault();
doHiding();
});
});
function doHiding() {
$("div.thread").each(function() {
$(this).hide();
});
}
try
href="#"
its work for this case