jQuery - how to combine many click operations - javascript

I need to react to click events of dynamically created elements. Is there an elegant way to combine the functions, that I only have to listen once to a click in the body? Some of the elements have several classes.
HTML
<div class="dropDown blueBG"></div>
JS
$("body").on('click', '.dropDown', function(e){
.......
});
$("body").on('click', '.aButton', function(e){
.......
});
$("body").on('click', '.aForm', function(e){
.......
});

Combine them in the selector using a comma to separate them:
$("body").on('click', '.dropDown, .aButton, .aForm', function(e){
});
If you want to find out what was clicked you can use $(this).is('.dropDown') or $(this).hasClass('.dropDown').

Try to use the multiple selector,
same function for all the elements:
$("body").on('click', '.dropDown,.aButton,.aForm', function(e){
});
different functionality for different elements:
$("body").on('click', '.dropDown,.aButton,.aForm', function(e){
if ($(this).is('.dropDown')) { }
else if ($(this).is('.aButton')) { }
else { }
});

Create a new class that is common to the elements that you would like to handle the click event with:
HTML:
<div class="dropDown blueBG clickable"></div>
JS:
$("body").on('click', '.clickable', function(e) {
.......
});

Attaching an event on the dynamically created elements(tags are being created through Java script) responses abruptly.
So for a definite result access the parent element of the dynamically created tags and invoke an on("Event") function.
Belowmentioned is the sample code:-----
$(".parent").on("click",".newele1,newele2",function()
{
-----content-------------
});
For a clear picture please refer to this js fiddle example.
//jsfiddle.net/5SyS3/6/

Related

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:
$(document).on('click', 'name=[buttonName]', function() {});
I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.
Thanks
Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:
$(document).on('click', '[name="buttonName"]', func);
To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
// do something...
}
});
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
alert('Hello!');
}
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>
You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.
document.querySelector("button[name='buttonName']").addEventListener("click", function(){
alert("Hello, World");
});
<button name="buttonName">Click me</button>
The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.
You can use getElementByName to add click event to your button which is dynamically render
document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

How to get the current/this object on button click using bind event?

I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});

javascript click event subscription in appended html

I have this javascript code that appends html code into a tag:
var html ='<ul class="nav well-tabs well-tabs-inverse mb10">';
html +='<li class="active"><a id="#tab_'+this.my.user+'" data-toggle="tab">'+this.my.user+'</a></li>';
var users = this.my.community_users;
for (i=0;i<users.length;i++) {
if (users[i].user != this.my.user)
html +='<li><a id="#tab_'+users[i].user+'" data-toggle="tab">'+users[i].user+'</a></li>';
};
html +='</ul>';
$(html).appendTo("#Dashboard");
I want to capture the any tab click event and alert the id of the tab being activated by the click. If I simply add this code after the previous javascript code
$('a[data-toggle=tab]').click(function(){
alert(this.id);
});
this is not working. On the other hand if I settimeout after the second it works:
setTimeout(function(){
$('a[data-toggle=tab]').click(function(){
alert(this.id);
});
}, 1000);
I don't like much this to settimeout so what would be a cleaner solution to this? I guess the event suscription is being done before the html code is appended?
For dynamically created elements in jQuery you should use a static parent to select the dynamic element, in your case an example can be:
$('#Dashboard').on('click', 'a[data-toggle=tab]', function(e){
//your code here
});
OR even the document itself
$(document).on('click', 'a[data-toggle=tab]', function(e){
//your code here
});
you can use delegate() or on() for this purpose
see delegate and on
Note: As of jQuery 1.7, .delegate() has been superseded by the .on() method
In your case you are not giving selection with respect to parent
$("parent_selection").on('click', 'actual_element' ,function(){});
your case
$(document).on('click', 'a[data-toggle=tab]', function(e){
});

Get custom css property with a function

This is my code :
<html>
<body>
<button class="myclass" data-card-id="1">Save</button>
</body>
</html>
My question is how whould look like a function that when user click on any of "myclass" buttons submit a variable with data-card-id of the specific card in a php file.
Thank you ! :)
this is using Jquery:
$(".myclass").click(function(){
$(this).attr( "data-card-id" );
});
JSFIDDLE - http://jsfiddle.net/q5j8z/11/
see browser console for data display
// change the selector "ul li a" to your button
$('ul li a').click(function (e) {
e.preventDefault();
var value = $(this).data('value');
$('.button').data('value', value);
console.log($('.button').data('value'));
});
$('.button').click(function (e) {
e.preventDefault();
console.log($(this).data('value'));
});
This can be accomplished through an additional selection feature. I believe "data-card-id" is an attribute of your html tag, so you have two choices.
Bind the click to the element using the selector or delegate it to the body of the document, I think you'll see how either way works here.
Option 1. The advantage here is that when click events bubble up to the body this will check and execut appropriately, even if other buttons are added to the page after this code is executed. This is jquery's click delegation feature
$('body').on('click', 'button[data-card-id="1"]', function(){
//perform your action
});
Option 2. This binds the click event to the object itself. This can be more straight forward and has its advantage in simplicity.
$('button[data-card-id="1"]').click(function(){
// perform some action
});
And of course you have a plethora of other approoaches......
or
$('button').each(function(){
if($(this).attr("data-card-id") == '1'){
$(this).click(function(){
//some action
});
}
});
There are other approaches, too. Let me know if none of these seem to work.
JS FIDDLE DEMO
The most simpler would be to use this code -- >
just change this card-id to this cardid
HTML
<button class="myclass" data-cardid="1">Save</button>
<button class="myclass" data-cardid="2">Save</button>
JS
$(document).ready(function(){
$(".myclass").on('click',function(){
var cid = $(this).data("cardid");
alert(cid);
});
});

How to disable links even after adding a new link?

I would like to disable clicking on links in the preview and show an error message instead. I came up with a simple solution:
<div id="preview">
<p>There is a sample link that should not follow to google.com</p>
<ul></ul>
</div>
<button id="btn">Add a new link</button>
JavaScript code:
$('a').on('click', function () {
alert("links are disabled");
return false;
});
$('#btn').on('click', function () {
$('#preview ul').append('<li><p>another link</p></li>');
});
It works perfectly fine for the already existing links but not for the new links added via the button.
How to disable links even after adding a new link?
I would like to keep the logic for disabling links out of the code for adding a new links (as there are multiple places that are adding a new link)
JS fidddle: http://jsfiddle.net/bseQQ/
To capture events on dynamic elements you need to use a delegated selector:
$('#preview').on('click', 'a', function () {
alert("links are disabled");
return false;
});
This is because events are attached on load, and obviously dynamic elements do not exist at that point. A delegate event is attached to a parent element, but only fired when the filtered selector bubbles the event through the DOM.
Working demo http://jsfiddle.net/P6Hbg/
API: .on - http://api.jquery.com/on/
This should fit your cause :)
code
$(document).on('click','a', function () {
alert("links are disabled");
return false;
});
You'd better use event delegation:
$('#preview').on('click', 'a', function() {
alert('links are disabled');
return false;
});
Here #preview is used as a static parent element.
$('#btn').click(function () {
$('#preview ul').append('<li><p>another link</p></li>');
});

Categories

Resources