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

$('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.

Related

change div class,id,.. in every click

I trying to run code to change div id,class,... in every click but I don't
know how this my js code :
<div class="up_vote_bt upvote_hide" title="Delete up vote" onclick="upvoteHide()" id="hideupvote"></div>
<script>
$(document).ready(function() {
$("#upvote").click(function() {
document.getElementById("upvote").setAttribute("class","up_vote_bt upvote_hide");
document.getElementById("upvote").setAttribute("title","delete up vote");
document.getElementById("upvote").setAttribute("onclick","hideupvote()");
document.getElementById("upvote").setAttribute("id","hideupvote");
});
});
</script>
<script>
$(document).ready(function() {
$("#hideupvote").click(function() {
document.getElementById("hideupvote").setAttribute("class","up_vote_bt");
document.getElementById("hideupvote").setAttribute("title","up vote");
document.getElementById("hideupvote").setAttribute("onclick","upvote()");
document.getElementById("hideupvote").setAttribute("id","upvote");
});
});
</script>
if you're using jQuery why not do this?
$(document).ready(function(){
$('#upvote').click(function(){
//$(this) for just this element
if($(this).hasClass('upvote_hide')){
$(this).attr('title','Up vote');
upvote();
}else{
$(this).attr('title','Delete up vote');
hideupvote();
}
$(this).toggleClass('upvote_hide')
});
});
toggleClass() will either add or remove upvote_hide if it doesn't exist or exists.
attr() will alter the attribute much like setAttribute()
For my example there is no need to alter the eventHandlers or in your case setting the attribute onClick to the function. I'ts all done in the jQuery event hander function. So your functions that you're passing to the onclick attribute are called within the function.
When you attach an event handler via jQuery using the
$("#upvote").click(function() { ... });
mechanism, jQuery will directly attach the handler to the elements in the query result set. This means that the handler will be there, whatever the ID changes to in the future.
What you can do is to attach a delegated handler to the document like this.
$(document).on("click", "#upvote", function() { ... });
$(document).on("click", "#hideupvote", function() { ... });
See this article for a deeper explanation
Also, setting the onclick attribute is meaningless in this case and you should remove those lines.
However, changin IDs of elements is not a good practice. An ID should mean a unique identifier for a DOM node, which is not expected to change. I would rather toggle classes here.

click event to a JQuery object before adding it to the DOM

Attaching the click event to a JQuery object before adding it to the DOM is done like this I believe.
$('.Button').on('click', '#Your-Selection', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Is there a way to attach it to a span child of #Your-Selection. This does not work but something like:
$('.Button').on('click', '#Your-Selection span', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Please use like this
$(document).on('click', '#Your-Selection span', function () {
console.log("yeahhhh!!! this will work for you :)");
});
this will attach click event to the span child of #Your-Selection
I think you are not asking the right question, please
take a look at the jquery on method documentation:http://api.jquery.com/on/
If neither .Button exists (on DOM load) is better to attach it to the body, but if it
exists is better attach to body that the whole document, or the closest tag you have in DOM
You should do something like this:
$("body").on("click", ".Button #Your-Selection span", function(){
//whatever you want
});
As per the jQuery API documentation I have doubts with below solutions. The correct way I think is like as follows:
$('#Your-Selection').on('click','span',function(){
console.log('yeahhhh!!! this will work');
});
so if the button is inside the span you can modify the above code as follow
$('#Your-Selection').on('click','span .Button',function(){
console.log('yeahhhh!!! this will work');
});
So the event only need to be bubble up one level. If you use document or body event need to bubble up so many levels if your HTML structure is complex.

Cant select ids that I loaded with jQuery

I understand that you need to use ".on" to use code that you loaded with jquery after the page has loaded. (At least I think it works that way)
So I tried that but it somehow just doesn't do a thing at all. No errors in the console either.
$("#forgot_password").click(function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("#toLogin").on("click", function(){
alert("Hello");
});
So when I click on #forgot_password it does execute the first click function. But when I click on #toLogin it doesn't do anything and I think its because its loaded with jquery when I click on #forgot_password
Try this
$("#loginPopupForm").on("click", "#toLogin", function(){
alert("Hello");
});
You need to bind to an element that is present when the page loads, like body for example. Just change your code to what is shown below
$("body").on("click", "#forgot_password", function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("body").on("click", "#toLogin", function(){
alert("Hello");
});
You are setting the on to the wrong thing. You want it to be:
$(document).on('click', '#toLogin', function() {alert('hello') });
The id isn't there until you do the other click event, so jQuery is not finding any element to set the click event on. You need to have an element that has been rendered in the DOM to set the event on.
You are totally right about the problem : on() targets only elements that are already existing as it runs.
What you need in jQuery is called Delegated event and is well explained on the Jquery doc page.
The difference in the code is thin, but it's how you're supposed to do.
You have to specify the parent element
$("#toLogin").on("click","#loginPopupForm", function(){
alert("Hello");
});
in the 2nd argument of the on

jQuery select all elements with a common class

I want to handle a click event across a set of links so tried to approach this by adding a secondary class like following:
Test 1
Test 2
Test 3
Don't handle this one
Then tried this jquery selector to select the "external" class on links:
$('a.external').click(function(e) {
do something here...
});
However this isn't working like I expected. What's the right way to handle this? Should I just use a wildcard selector like the following or is there a better way?
$('[class^="someclass"]').click(function(e) {
....
});
What you have is exactly right (though the e probably isn't necessary in function(e) in your case).
Test 1
Test 2
Test 3
Don't handle this one
<script>
$('a.external').click(function(e) {
// will print the href in a javascript alert box
alert( $(this).attr('href') );
});
</script>
As far as I can tell the only possibility is that your <script> is actually above your <a> tags -- your script can't add the click listeners to the anchors because they wouldn't exist yet.
If so, you'll need to wrap the javascript in $(document).ready( function(){ /* code here */ });
Also, no need for the external class, just use the "select all absolute anchors, but not the ones linking to my domain" selector: $('a[href^="http://"]').not('[href^="http://mydomain.com"]')
I'm going to guess that your issue is that clicking the links actually makes it navigate somewhere? You need to tell the browser to ignore the normal link behavior. Otherwise your click function will run and then it will immediately navigate to the 'href' url. Also make sure this is all wrapped in a ready function.
$(function() {
$('a.external').click(function(e) {
// Do whatever
e.preventDefault();
});
});
I tried it out in jsFiddle and it works.
You have an extra parenthesis on the click() function.
Notice have your function(e) you have close parenthesis, remove that.
You should end up with this:
$('a.external').click(function(e) {
do something here...
});
try : http://jsfiddle.net/n6JJ3/
$('a.external').click(function() {
jQuery(this).css('background','red');
});​

Can I apply click event on body element?

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/

Categories

Resources