Removing an onclick event from a div with javascript - 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>

Related

How to detect classname with onclick event

I want to be able to click on an element and then depending on whether it has a specific class name, do something.
Here is what I have so far:
<div class="my-class" onclick="myFunction()"/>
function myFunction() {
if (element.classList.contains("my-class")) {
//do something
}
}
where am I going wrong?
You need to pass the click event then get the target element which in this case is the clicked element.
function myFunction(event) {
if (event.target.classList.contains("my-class")) {
alert("I Do things becuase i have (my-class)")
}
}
<button class="my-class" onclick="myFunction(event)">Click me</button>
<br/>
<br/>
<br/>
<br/>
<button onclick="myFunction(event)">I Do nothing</button>
As #collapsar mentioned in comment, element is't set. I recommand you to use addEventListener and event.target.
document.getElementById("your-element").addEventListener("click", () =>{
if (event.target.classList.contains("my-class")) {
console.log("your-element has \"my-class\" class")
}
})
<div id="your-element" class="my-class">Click</div>
When the HTML element rendered statically you should consider two things:
Wait for the DOM ready event in order to make modifications on the element.
Attach the event dynamically, making sure that you bind the event handler to new elements after adding them to the DOM.
HTML
<div class="my-class" />
Javascript
function myFunction(event) {
var element = event.target;
if (element.classList.contains("my-class")) {
//do something
}
}
document.addEventListener("DOMContentLoaded", function(event) {
// DOM is ready
const elements = document.getElementsByClassName("my-class");
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction);
}
});

Javascript define function to be invoked first on onclick event using addEventListener or other method

i have legacy js code which i dont what to touch defined in script A.js ..
it have simple onlick event and function attahced to it
$(document).ready(function () {
//jquery onclick
$("#create_button").click(function (e) {
.....
}
}
//html
<button class="btn btn-primary" id="create_button"
name="create_button">
Create New app
</button>
Then to add functionality to this button im defining in doing this is loading in my second script script B.js which comes after A.js
$(window).on('load', function(){
document.getElementById("create_button").addEventListener("click", () => {
self.MyFirstFunction()
}, false);
}
my question is how can i defined that self.MyFirstFunction() will allways triggred first ?
set useCapture to true when adding event listener to the element:
For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. Event listeners in the “capturing” phase are called before event listeners in any non-capturing phases.
$('#element').click(function(){
console.log("first registered Handler in source code")
})
document.getElementById("element").addEventListener("click",function(e){
console.log("second registered Handler in source code")},true); // Notice the last argument is true
#element{
width:200px;
height:100px;
background:lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element"></div>
You can set the useCapture flag of the eventListener to give it the highest priority over other eventListeners.
In your case:
scriptB.js
$(window).on("load", function () {
document
.getElementById("create_button")
.addEventListener("click", () => self.MyFirstFunction(), true);
});
Demo:
let button = document.querySelector("#button")
button.addEventListener("click", () => {
console.log("I was added first")
})
button.addEventListener("click", () => {
console.log("I was added second")
}, true)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Demo Button</button>

Add click event on a dynamically created element in Javascript

I am trying to add a click event on an element which i create dynamically in Vanilla JS. With jquery its super simple all i would do is
$(document).on('click','.el', function() {
//somecode
})
However with Vanilla JS (because i'm using react) i can't do the same thing.
I've tried adding the dynamic element as an argument just like i would in jquery but no money.
I'm sure it can be done just not the way i'm thinking. Any ideas?
I tried
let div = document.createElement('DIV')
div.classList.add('el')
document.addEventListener('click','.el', function() {
//some code
})
I also tried
document.addEventListener('click',div, function() {
//some code
})
None of these methods worked
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
https://jsfiddle.net/yu1kchLf/
You could simply use and onclick function and just call it as variable from your dynamically added elements.
Live Demo
//Create function
let button = document.createElement('button');
button.classList.add("myBtn");
button.innerText = 'Click Me';
button.onclick = myFunction //assign a function as onclick attr
document.body.appendChild(button);
//Call function
function myFunction() {
console.log('I am being called from dynamically created button')
}
i think what you are missing is appending the element you created to your DOM.
have a look at this:
var createDiv = function() {
let div = document.createElement('DIV');
div.id = 'el';
div.innerHTML = '<b>hey</b>';
div.classList.add('styles');
document.body.appendChild(div);
div.addEventListener('click', function() {
alert('Look here');
})
};
here's a fiddle so you can playaround: https://jsfiddle.net/khushboo097/e6wrLnj9/32/
You can do something like the following:
const d=document.getElementById("container");
document.addEventListener('click', function(ev) {
if (ev.target?.classList.contains('el')) {
console.log("My .el element was clicked!");
ev.target.classList.contains("segundo") &&
(d.innerHTML+='<p class="el">another clickable paragraph</>');
}
})
<div id="container"><h2>Something unclickable</h2>
<p class="el primero">A clickable paragraph!</p>
<p class="otro primero">something unclickable again ...</p>
<button class="el segundo">add clickable element</button>
</div>
The event handler is attached to the document itself but will only fire the console.log() if the ev.target, i. e. the clicked element, is of class "el".

single onclick function for buttons with a similar id pattern - 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)
})
});

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