How to remove the element's event handler and set it back? - javascript

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

Related

how to register jquery events to dynamically added elements which are not child elements

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

jquery 1.7 click event after append not working

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

Toggle onClick jquery

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

JavaScript works in JSFiddle but not in html file on a browser

I'm trying hook up a checkbox check event with additional events (such as a dialog display). However, I can't seem to get the click event working when I'm testing my html file in a browser. It does work in JSFiddle, though, which is very strange.
http://jsfiddle.net/rEgAX/1/
My HTML:
<label><input type="checkbox" name="checkbox-0" id="myCheckbox" /> Completed </label>
My JavaScript:
var countChecked = function() {
if ($("#myCheckbox").is(":checked"))
{
alert('checked!');
}
};
$( "input[type=checkbox]" ).on( "click", countChecked );
The html file that I wrote:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script>
// On clicking of the completed checkbox, we want to pop up a dialog for confirmation.
var checkboxClicked = function() {
if ($("#myCheckbox").is(":checked")) {
alert('checked!');
console.log('checked!')
}
};
$( "input[type=checkbox]" ).on( "click", checkboxClicked );
</script>
</head>
<body>
<label><input type="checkbox" name="checkbox-0" id="myCheckbox" /> Completed </label>
</body>
</html>
You must place your code inside
$(document).ready(function(){
...
});
Since your script comes before your checkbox is rendered.
EDIT
You might run unto a problem with my first answer. Thanks to Omar's comment and reference
It should be this way rather than .ready() function:
$(document).on('pageinit') {
...
});
By default, jsFiddle will wrap your code in an load handler.
Try wrapping your code in:
$(window).load(function(){
var countChecked = function() {
if ($("#myCheckbox").is(":checked"))
{
alert('checked!');
}
};
$( "input[type=checkbox]" ).on( "click", countChecked );
});

jquery hide hides and immediately displays again

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

Categories