single onclick function for buttons with a similar id pattern - JavaScript - javascript

I want to reduce the code.
function one() {
console.log("hai");
}
document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I want the above 2 lines of code reduced to one.
A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.

You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:
function one() {
console.log("hai");
}
Array.prototype.forEach.call(
document.querySelectorAll('[id^=dealsButton_]'), function(e) {
e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>
If the markup is dynamically loaded you can base it on a static element like this:
function one() {
console.log("hai");
}
document.addEventListener('click', function(e) {
if (e.target && /^dealsButton_/.test(e.target.id))
one();
})
// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;

Are you looking for something like this:
function onClick(){
//single handler
}
$('[id*="dealsbutton_"]').click(onClick)

Here is a solution where you can choose ID name as u wish without a specific pattern of name.
<html>
<body>
<div id="abc">one</div>
<div id="def">two</div>
<script type="text/javascript">
function one() {
console.log("hai");
}
function addOnclickFunc (func, idArray){
idArray.forEach(function(element) {
document.getElementById(element).onclick = func;
})
}
addOnclickFunc(one,["abc","def"])
</script>
</body>
</html>

you use jQuery with regex for this
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
//code here
})
});
if want to make the function call names dynamically. pass it as data attribute to button element and call it using eval function
<button id="dealButton_1" data-click="one"></button>
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
var function_call = $(this).attr('data-click')
eval(function_call)
})
});

Related

Removing an onclick event from a div with javascript

Basically what the title says this is the code that I've tried but it doesn't work:
<div id="box" onclick="doSmt(var1, bar2)">
if (condition){
box.removeEventListener("click" , doSmt)}
I think it's better if you remove the onclick event instead of that attempt
//onclick function
function doSmt(){
console.log("something");
}
//remove onclick event, this will be inside your if condition
document.getElementById('box').removeAttribute("onclick");
<div id="box" onclick="doSmt()"> div</div>
What what I read at MDN for removeEventListener you can't remove an event listener that is part of the HTML attribute. So there's two options:
Add the event listener on page load
onClickHandler = () => doSmt(var1, var2);
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('box').addEventListener('click', onClickHandler);
});
// and later
if (condition) {
document.getElementById('box').removeEventListener('click', onClickHandler)
Or if you can't modify the HTML you could modify doSMT to watch for a disabled bit.
let disableBox = false;
function doSmt() {
if (disableBox) return;
// ...
}
if (condition) {
disableBox = true;
}
Or
it can be removed by first accessing the element and then setting the attribute to null
<div id="myDiv" onclick="handleClick()">Click me</div>
<script>
function handleClick() {
alert("Div was clicked!");
}
// Remove the onclick event from the div
const div = document.getElementById("myDiv");
div.onclick = null;
</script>

How do I add another onclick function after the vote function? [duplicate]

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

adding element using loop in jquery doesn't appear in dom

I am adding elements using a json call. The issue I have is that if I append an item outside the loop it appears in the DOM and I can select it, if I appended in the loop I cannot select it?
Any help would be appreciated.
<ul data-role='listview' class='ui-listview' id="DivLogOut" >
</ul>
<script type="text/javascript">
$(document).ready(function () {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
$.get("api/StaffLoggedIn.ashx?loid=" + loid, function (data) {
var jsonobj = $.parseJSON(data);
$(jsonobj).each(function (i, item) {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
})
})
$(".PersonLogout").click(function () {
alert("test");
})
})
</script>
Dynamically appended element use with on()
$(document).on("click",".PersonLogout",function () {
alert("test");
})
when added dynamically, you need to re-add the listener to your DOM element, this way Jquery knows which one to call. i suggest you add your .click method in a function that you can call after the async loop is done (your $.get) EX:
<ul data-role='listview' class='ui-listview' id="DivLogOut">
</ul>
<script type="text/javascript">
$(document).ready(function() {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
$.get("api/StaffLoggedIn.ashx?loid=" + loid, function(data) {
var jsonobj = $.parseJSON(data);
$(jsonobj).each(function(i, item) {
$("#DivLogOut").append($("<li class='PersonLogout'>TEST ITEM</li>"));
})
addListener();
})
function addListener() {
$(".PersonLogout").click(function() {
alert("test");
})
}
addListener();
})
</script>
Please use .on instead of .click method. .on method will work for dynamically added elements.
$(document).on("click",".PersonLogout",function () {
//You can access the item using $(this)
});
You're creating an element after the document has loaded. AFAIK elements that are dynamically created after the document has loaded has no event binded on it.
What you can do is to bind the event on document. Remove the click event in the document ready function.
$(document).on('click', '.PersonLogout', function()
{
alert('I have been clicked!');
});
You need to listen the event outside the reloaded view, apparently $("#DivLogOut").
$("#DivLogOut").on('click', '.PersonLogout', function(){
....
});
For sure, it works ;)

Apply A Function to All Links on Page

i have my all links on page like this :
Example
But Now I Want All Links With Following OnClick Function like this:
<a onclick="show();" href="http://example.com">Example</a>
can any one tell me jquery or javascript code to add above function to all links on body, thanks
Some answers have suggested to use jQuery's click() function. That's alright as long as you don't expect to add new links dynamically using javascript.
This click handler will bind on the <body> element, and fire whenever a <a> element inside it is clicked. The advantage with this over $('a').click(...) is that all <a> tags don't need to be present on page load:
$(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
show();
});
});
Fiddle: http://jsfiddle.net/Lubf6gjw/2/
EDIT: Here's how to do it with pure javascript:
document.querySelector('body')
.addEventListener('click', function (event) {
if(event.target.tagName === 'A') {
event.preventDefault();
show();
}
});
http://jsfiddle.net/pymwsgke/1/
$(function(){
$("a").click(function(){
show();
}
});
If you want to prevent the browser from following the href, you can just add a preventDefault call
$(function(){
$("a").click(function(e){
e.preventDefault();
show();
}
});
Note that this will not actually append the onclick= to the <a> tags. If you want to do that, you can do it this way:
$("a").each(function(){
$(this).attr("onclick", $(this).attr("onclick")+";show();");
});
Using pure Js
function show (event) {
event.preventDefault();
// do somethink
}
var anchors = document.querySelectorAll("a");
for(var a = 0; a < anchors.length; a++) {
anchors[a].addEventListener("click",show,false)
}

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

Categories

Resources