Can I apply click event on body element? - javascript

I am willing to create div's dynamically on double clicking anywhere on the page. Can I apply click event to body element?
Here's what I tried so far:
jQuery("document").ready(function(){
alert("click");
jQuery("body").dblclick(function(event){
alert("click");
});
});

Yes:
// Example, needs some IE compatibility work
document.body.ondblclick = function (evt) {
createNewDiv(evt.pageX, evt.pageY);
}
Is there something you tried that didn't work?
Responding to your comment,
"can you tell me whats wrong with this one"
jQuery("document").ready(function(){ alert("click"); jQuery("body").dblclick(function(event){ alert("click"); }); });
The problem is you're using a tag selector to look for the document object. jQuery("document") will look for an element in the document called <document>, which doesn't exist. You need to just pass in the document object, so:
jQuery(document).ready(function(){
alert("click");
jQuery("body").dblclick(function(event){
alert("click");
});
});
Also, by default a <body> element is only as big as its content, so if you apply the dblclick event to a <body> with no content, only the top-left part of the document will fire the event. Instead, you want to apply it to the document object instead:
jQuery(document).dblclick(function(event){
alert("click");
});
Example: http://jsfiddle.net/a4DKC/2/

Related

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

Jquery script inside the loaded layer is not working

I have following code snippet in jquery when we click on layer 62 which loads a layer "loaded-page" from a page test.html as follows.
<script>
$(document).ready(function(){
$('#62').on('click', function(e) {
$("#62" ).load( "test.html #loaded-page" );
});
$('#loaded-page').on('click', function(e) {
alert('test');
});
});
</script>
<div id="62">Layer62</div>
Test page coding
<div id="loaded-page">Loaded page</div>
MY issue is when we click on layer loaded-page inside DOM, the alert test is not functioning. Can anybody suggest a solution for this ? If needed I can prepare a fiddle for this
This already has an answer, but essentially what you are looking for is event delegation
When you bind the event in your code, that element doesn't exist yet.
So, you bind the event differently, so that it will respond to dynamically added content:
$(document).on('click', '#loaded-page', function(e) {
alert('test');
});
NOTE: Without knowing your html structure, I can't provide the best solution, but I CAN tell you that you do not want to use document if possible. Instead, you should use the nearest parent that exists when the DOM is initially loaded. In your case, my guess is that this would work:
$('#62').on('click', '#loaded-page', function(e) {
alert('test');
});
because that when you bind the
$('#loaded-page').on('click', function(e) {
alert('test');
});
maybe that the #loaded-page element is not be loaded into the document,so can't find it
the better way is :
$(document).delegate('#loaded-page','click',function(){
alert('ok')
})

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

$('body').on('click', '.anything', function(){})

$('body').on('click', '.anything', function() {
//code
});
doesn't work for anything right now and I can't figure out why. I'm able to anchor to anything else, say I just toss a #wrap div right inside the body. Then I'm able to do
$('#wrap').on('click', '.anything', function() {
//code
});
for any element I want.
Any idea what I could have done to disable this ability on the body element?
Thanks!
You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click','body *',function(){
// $(this) = your current element that clicked.
// additional code
});
You can try this:
You must follow the following format
$('element,id,class').on('click', function(){....});
*JQuery code*
$('body').addClass('.anything').on('click', function(){
//do some code here i.e
alert("ok");
});
If you want to capture click on everything then do
$("*").click(function(){
//code here
}
I use this for selector: http://api.jquery.com/all-selector/
This is used for handling clicks: http://api.jquery.com/click/
And then use http://api.jquery.com/event.preventDefault/
To stop normal clicking actions.

jQuery function not binding to newly added dom elements

Here's index.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() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });

Categories

Resources