This question already has an answer here:
Consolidate Click Functions
(1 answer)
Closed 6 years ago.
I have the below jquery functions which you can find in this code pen that I would like to simplify.
I'd like to write the below javascript more concisely by writing a function that creates all the below functions, since the only difference are the following strings: name1, name2, name3, etc.
Javascript
$('#name1').on('click', function(){
document.getElementById("name1").innerHTML = "name1";
});
$('#name2').on('click', function(){
document.getElementById("name2").innerHTML = "name2";
});
$('#name3').on('click', function(){
document.getElementById("name3").innerHTML = "name3";
});
$('#name4').on('click', function(){
document.getElementById("name4").innerHTML = "name4";
});
$('#name5').on('click', function(){
document.getElementById("name5").innerHTML = "name5";
});
$('#name6').on('click', function(){
document.getElementById("name6").innerHTML = "name6";
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
I think this is the simplest solution:
$('button').on('click', function() {
$(this).html($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>
If you want this to work on specific buttons you can use $('#name1,#name2,#name3...').on.
If they all have specific class you can use $('.specific-class').on.
If they all exists inside some specific element you can use $('div#id1 button').on
And so on...
You're targeting every button on the page, so the selector can be simpler:
$('button').on('click', function(){
//
});
And you're setting the "currently clicked element" to the value of its id, which can be more general:
$('button').on('click', function(){
this.innerText = this.id;
});
Note: If this selector is overly simple (you don't want to target every button on the page), you can still use the original list of id values as a single selector. Perhaps something like:
$('button[id^="name"]').on('click', function(){
this.innerText = this.id;
});
Or even:
$('#name1, #name2, #name3, #name4, #name5, #name6').on('click', function(){
this.innerText = this.id;
});
Sometimes it's also appropriate to assign click handlers to a single parent element, especially if there could be many matching elements. Something like this:
$(document).on('click', '#name1, #name2, #name3, #name4, #name5, #name6', function(){
this.innerText = this.id;
});
The difference here is that instead of assigning the handler function to each matching element, only one handler function is assigned to the document and the selector for the target button elements is evaluated on the fly when executing that handler.
Condense your jQuery to this:
$('button[id^="name"]').on('click', function(){
var thisID = $(this).attr("id"),
thisNum = thisID.replace("name", "");
document.getElementById("name" + thisNum).innerHTML = "name" + thisNum;
});
An alternative, pure jQuery solution would be this:
$('button[id^="name"]').on('click', function(){
var t = $(this),
thisID = t.attr("id");
t.html("name" + thisID.replace("name", ""));
});
Related
Please don't make it Duplicate, I just want to understand If I wrote my code wrong, All thought I checked it couple of times.
I can't understand way my code dosen't work.
Js:
var p1button = document.querySelector("#p1");
var p2button = document.getElementById("p1");
//p1 btn
for(var i = 0; i < p1button.length; i++){
p1button[i].addEventListener("click", function(){
alert("clicked") });
};
html:
<button id="p1">Player One</button>
<button id="p2">Player Two</button>
My codepen
It doesn't work because p1button is already an ElementButton, not an Array where you have to use [0] to get the element from.
var p1button = document.querySelector("#p1");
p1button.addEventListener("click", function(){
alert("clicked")
});
<button id="p1">Player One</button>
whereas, is you had multiple class .btn elements your code would make sense, since .getElementsByClassName or .querySelectorAll do actually return an array-like NodeList:
function doThaChng () {
alert("clicked!");
}
var btn = document.querySelectorAll(".btn");
for(var i=0; i<btn.length; i++) {
btn[i].addEventListener("click", doThaChng);
}
<button class="btn">Player One</button>
<button class="btn">Player Two</button>
Or in ES6
const btn = document.querySelectorAll(".btn");
const doThaChng = () => alert("Clicked");
[...btn].forEach(el => el.addEventListener("click", doThaChng) );
<button class="btn">Player One</button>
<button class="btn">Player Two</button>
p1button is not an array but a DOM element.
Try keeping just:
p1button.addEventListener("click", function(){
alert("clicked")
});
From the documentation of querySelector():
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
Try it out (open up Developer Tools to see the console):
console.log(document.querySelector("button"));
So you don't need (and you can not) iterate over p1button, because it's a node instead of an array.
It's because querySelector and getElementById returns a single DOM element and not an array of DOM elements. So your for loop is useless and try to add an event listener on an undefined value.
Here is a correct way to listen for click event
var p1button = document.querySelector("#p1");
p1button.addEventListener("click", function(){
alert("clicked")
});
Here you can find more infos about querySelector and getElementById.
I try make simple case with 2 button like this.
$(document).ready(function(){
function tes(){
var result;
$("#wrapper").html('<button id="btn2">Button 2</button>');
$("#btn2").click(function(){
result = "How to passing this value?, After button 2 clicked"
})
return result;
}
$("#btn1").click(function(){
alert(tes());
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div>
How to pass value of variable result after button2 click, where element for button2 exists after button1 click?
Ok as you've no problem using jQuery. I think this is what you want
var result = '';
function tes(){
document.getElementById("wrapper").innerHTML = '<button id="btn2">Button 2</button>';
result = "How to passing this value?, After button 2 clicked"
}
var button = document.getElementById("btn1");
button.onclick = function(){
tes();
}
$(document).on('click', '#btn2', function(){
alert(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<div id="wrapper"></div>
Ps. You're trying to bind events on dynamically created elements and the way you're doing in your code is not the proper way. You can do that $(document).on('click', 'DOM_Element', function(){}). Just to let you know so you should have an idea when working on JS in future
Hello guys I try to figure out how can I pass an element's attributes which I clicked in a different function
To be specific I have a dozen of elements with the same className = online
However each of the elements has one unique id which I assigned to them dynamically.
I use $(document).on because I want to listen on the document, for a click because the elements with className=online are created dynamically too.
$(document).on("click", ".online", isInPrivateChat);
How can I then in a different function for example
function TakeTheidfTheElement(){
//take the id of the element i clicked
}
I know I should use jquery method .attr('id') but cant really make it work.
Thanks
Working fiddle.
You could simply get the id from the callback function isInPrivateChat using this.id like :
function isInPrivateChat(){
alert( this.id );
}
Hope this helps.
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(){
console.log( this.id );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='online' id='id_1'>Btn 1</button>
<button class='online' id='id_2'>Btn 2</button>
<button class='online' id='id_3'>Btn 3</button>
Carry the ID through:
$(document).on("click", ".online", function() {
isInPrivateChat($(this).attr('id')); /* <-- get id and pass it in */
});
then
function TakeTheidfTheElement(idPassed){
// do something with idPassed
}
For the record, Zacaria's answer is the better option - showing this is how you can use .attr('id')
You can pass the whole element to a sub function and there you can use JQuery or straight javascript to get the properties of the element.
$(document).on("click",".online",function() {
getMyId(this);
});
function getMyId(element) {
alert(element.id);
}
If you just wanted to pass the id through to the sub function you can do:
$(document).on("click",".online",function() {
getMyId(this.id);
});
function getMyId(elementID) {
alert(elementID);
}
Here's a fiddle of it working
check the below code snippet
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(event) {
anotherFunctin(event.currentTarget.id);
}
function anotherFunctin(id){
console.log(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="online" id="id">
click me
</div>
I'm using JavaScript (or jQuery) and I can't retrieve correctly the id of the button calling the event.
Here is a simplified example :
I have 2 buttons with the same class (the class is used for the listener) with id "button_1" and "button_2", I'll click on one of them, launch the event and get the correct id. Now, I'll click on the other button, launch the event and I still get the id of the first button.
Here is the code :
$(document).on('click', '.list-button' , function(e){
var target = e.target || e.srcElement;
var button_id = target.id;
alert(button_id);
}
or with jQuery :
$(document).on('click', '.list-button' , function(e){
var button_id = $(this).attr('id');
alert(button_id);
}
Both output only the first event caller. The second time, it'll launch the function but it's like " $(this) " is still the first event caller.
EDIT : I simplified too much my example, the alert is working fine and it was crashing later in the code. It was linked to wordpress and I had to undefine the variable to correct it. Thanks for your help even if my request was exceptionnaly useless, I guess you helped me to step back and reading step by step.
Your code works perfectly fine.
$(document).on('click', '.list-button', function(e) {
var button_id = $(this).attr('id');
alert(button_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="list-button" id="button1">Button 1</button>
<button class="list-button" id="button2">Button 2</button>
Make sure you check your HTML to have it right.
The code is working fine !
$(document).on('click', '.list-button', function(e) {
var target = e.target || e.srcElement;
var button_id = target.id;
alert(button_id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="list-button" id="button_1">Button 1</button>
<button class="list-button" id="button_2">Button 2</button>
In my html I have a screen with with about 25 thumbnails, and each of them has a like button in the format:
<input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like">
Where data-id is different for each image.
The idea is to then use that id to make a POST request to the facebook graph API and like the post.
I have a event listener like so:
$('#likeBtn').click(function () {
facebook.likePhoto(controller.likeReady);
});
The issue I am having is I am unsure how to grab that data-id from the element that is actually clicked.
Let me know if I can provide any more information.
Thanks
Use .data()
$('#likeBtn').click(function () {
var data_id = $(this).data('id');
facebook.likePhoto(controller.likeReady);
});
Read this
Id attribute must be unique . Use classes Instead.
change HTML
Use class likeBtn instead of id likeBtn as you said you have many buttons like this .
<input type="button" class="btn btn-primary btn-small likeBtn" data-id="545206032225604" value="Like">
Noe your js becomes
$('.likeBtn').click(function () {
var data_id = $(this).data('id');
facebook.likePhoto(controller.likeReady);
});
Read Two HTML elements with same id attribute: How bad is it really?
Updated after OP's comment
Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('click','.likeBtn',function () {
var data_id = $(this).data('id');
facebook.likePhoto(controller.likeReady);
});
Syntax
$( elements ).on( events, selector, data, handler );
Try this:
$('#likeBtn').click(function () {
var dataId = $(this).prop('data-id');
console.log(dataId); //or do something else
facebook.likePhoto(controller.likeReady);
});
Though, if I understand this correctly, do you have multiple elements with the id likeBtn?
$('#likeBtn').click(function () {
var id;
id = $(this).attr('data-id');
facebook.likePhoto(controller.likeReady);
});