Event listener not firing on click - javascript

I am creating a simple function to close a flash message div on click event, but my listener is not firing.
I wrote 3 different functions to try to get it working, but nothing is happening and Chrome console isnt telling me anything.
My first was in ES6 class style, this one:
class closeFlashMessages {
constructor () {
this.getFlashMessages = document.querySelector("#flash-messages");
this.addEventListeners();
}
close () {
console.log(this.getFlashMessages);
this.getFlashMessages.className = "hide";
}
addEventListeners () {
if(this.getFlashMessages)
this.getFlashMessages.addEventListener("click", this.close);
}
}
new closeFlashMessages();
My second was this:
(function (){
let getFlashMessages = document.querySelector("#flash-messages");
function close () {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
function addEventListeners () {
getFlashMessages.addEventListener("click", function () {
close()
});
}
addEventListeners();
});
My last one is this:
(function (){
let getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", close(getFlashMessages));
function close (id) {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
});
My HTML:
<div id="flash-messages">
<div class="flash success">
<p>Recept byl přidán do nákupního seznamu.</p>
</div>
</div>
But none of them worked!! I dont understand
With the first two, I was getting undefined on my this.getFlashMessages also not sure why.

My solution is not in ES6
function Init(){
var id = document.getElementById('flash-messages');
var msg = document.querySelector('.flash');
id.addEventListener('click',function(){
msg.className = 'hide';
});
}
Init();
see demo here

I am not very much familiar with ES6.
But if I try similar code sample on a javascript it will be as given below and I hope it will be almost similar in ES6 aswell.
var getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", function()
{
clicked(getFlashMessages);
});
function clicked(id){
console.log(id);
id.className = "hide";
}
Here, I am calling anonymous function, and its default argument will be event object as given in https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener.

Related

how to destroy a function in another function javascript?

Function:
function abc()
{
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label,$table_id);
}
abc();
function refresh()
{
abc().hide; // Need help at this.
}
<button class="refresh" onclick="refresh()">Refresh</button>
I'm trying to remove function/stop running abc() function, when refresh button was clicked.
Try this code, if abc is in the global scope:
window.abc = function() {
return false;
}
or you could do: window.abc = undefined when it's in the global scope.
when it's a method: delete obj.abc
You can pass param in your function and check condition like below.
function abc(arg) {
if (arg) {
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label, $table_id);
} else {
//Do what ever you want if needed
}
}
abc(true);
function refresh() {
abc(false)
}
Put all the code you only want to run once at the start inside window.onload
window.onload = function() {
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label,$table_id);
}
Wrap the function inside an object to delete it. You can use the window object or create a new one. Example:
const functions = new Object;
functions.abc = () => { /* do something */ };
functions.abc();
const refresh = () => {
if ('abc' in functions){ functions.abc(); delete functions.abc; }
else { /* will do nothing */ }
};
Solved :-)

Module overwrite previous attached window mouseup event

I am currently working on a javascript module which open and close boxes, tooltip or similar, the function works great the only problem is when I call it twice on a page where the 'boxes' classes are different the window mouseup event will be overwritten and only one of the two module instances of boxes can now be closed after opening them.
var boxRevealer = (function () {
var buttons;
var boxes;
var element;
var drp_active = false;
var boxConstruct = function (btns, bxs) {
buttons = document.querySelectorAll(btns);
boxes = document.querySelectorAll(bxs);
boxEvents();
};
var boxEvents = function () {
buttons.forEach(function (e) {
e.addEventListener("click", function (ee) {
element = document.getElementById(e.getAttribute("data-drp"));
element.classList.toggle("displayn");
drp_active = true;
});
});
window.addEventListener("mouseup", function (e) {
if (drp_active === true) {
if (!e.target.classList.contains("filt_holy")) {
boxes.forEach(function (e) {
console.log("ELEMENT");
console.log(e);
e.classList.add("displayn");
});
}
}
}, false);
};
return {
boxConstruct: boxConstruct,
boxEvents: boxEvents
};
})();
Here is how i call the module
window.addEventListener("load", function(e){
boxRevealer.boxConstruct(".head_drp_btn", ".head_drp");
boxRevealer.boxConstruct(".mkt_drp_btn", ".mkt_drp");
});
So my question is, should I always name the boxes the same, or is there a work around?
Just remove the event before adding it, I think the same event is getting called twice.
So updated code will be as follows:
// Attach an event handler to <div>
e.addEventListener("mousemove", myFunction);
// Remove the event handler from <div>
e.removeEventListener("mousemove", myFunction);
And remove the window event as well before adding it.

Consolidate function with wildcard?

I want to consolidate the following function into something more eloquent.
Basically I want to get element by id like "title#" and push "#" into the function so that if you click on title#x you will ReverseDisplay link#xcontent.
Appreciate any advice thank you.
document.getElementById("title1").onclick = function() {myFunction()};
function myFunction() {
ReverseDisplay('link1content');
}
document.getElementById("title2").onclick = function() {myFunction1()};
function myFunction1() {
ReverseDisplay('link2content');
}
document.getElementById("title3").onclick = function() {myFunction2()};
function myFunction2() {
ReverseDisplay('link3content');
}
document.getElementById("title4").onclick = function() {myFunction3()};
function myFunction3() {
ReverseDisplay('link4content');
}
document.getElementById("title5").onclick = function() {myFunction4()};
function myFunction4() {
ReverseDisplay('link5content');
}
document.getElementById("title6").onclick = function() {myFunction5()};
function myFunction5() {
ReverseDisplay('link6content');
}
document.getElementById("title7").onclick = function() {myFunction6()};
function myFunction6() {
ReverseDisplay('link7content');
}
document.getElementById("title8").onclick = function() {myFunction7()};
function myFunction7() {
ReverseDisplay('link8content');
}
You can use document.querySelectorAll():
const ReverseDisplay = x => console.log(x)
Array.from(document.querySelectorAll('[id^="title"]'))
.forEach(el => el.addEventListener('click', () =>
ReverseDisplay(`link${el.id.split('title').join('')}content`)))
<div id="title1">title1</div>
<div id="title2">title2</div>
<div id="title3">title3</div>
document.querySelectorAll() returns a NodeList, so we have to use Array.from() to be able to use array methods like forEach. Then we add a click event listener to each element using addEventListener() (see addEventListener vs onclick). Using split('title').join('') we remove the 'title' part from the ID and leave only the number. If you're wondering what are these ` and =>, see template literals and arrow functions.

Is it possible to bind to the Click event and not use an anonymous function -- I just want to call a named function

I have the following code. The first attempt at binding to click event does not work. The second way does. The first shows the alert "CheckBox1" during Page_Load. The second one shows the alert "CheckBox4" during the proper time -- during clicks.
$(document).ready(function () {
$(document.getElementById(checkBox1ID)).click( SetCheckBox1State(this.checked) );
$(document.getElementById(checkBox4ID)).click(function () { SetCheckBox4State(this.checked) });
});
function SetCheckBox1State(checked) {
alert("CheckBox2");
var radNumericTextBox1 = $find(radNumericTextBox1ID);
var wrapperElement = $get(radNumericTextBox1._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox1.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox1.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
function SetCheckBox4State(checked) {
alert("CheckBox4");
var radNumericTextBox2 = $find(radNumericTextBox2ID);
var wrapperElement = $get(radNumericTextBox2._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox2.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox2.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
Am I doing something improper? I'd rather not use an anonymous function...but maybe this just how things work?
This code:
.click( SetCheckBox1State(this.checked) );
Assigns the .click() function to be the output of this function: SetCheckBox1State(this.checked).
You will have to get rid of the argument (make it internal) and just pass the function name:
.click( SetCheckBox1State );

Adding onclick to div element yields "Result of expression 'document.getElementById('elem1')"[null]

is not an object" in the safari browser. The entire code is
function addLinks () {
var p0 = document.getElementById('Pic0').onclick = addLinkAction;
}
function addLinkAction () {
var el = document.getElementById('vid0');
el.style.display = "block";
el.play();
}
The functions work fine but safari continues to throw errors when the page is rendered and and on each click of the link. I'm only testing this in safari as it's a HTML5 - iPad/iPhone only media. thanks
Try this:
function addLinks () {
var p0 = document.getElementById('Pic0').onclick = function () {
var el = document.getElementById('vid0');
el.style.display = "block";
el.play();
};
}
Make sure the element exists. When you invoke addLinks do it on DOM ready or window.onload = function(){}. Alternatively, put the script before the end body tag.
assuming you call function addLinks() on document load/ready, try to add return false as last statement of this inner function
function addLinks () {
var p0 = document.getElementById('Pic0');
p0.onclick = function() {
addLinkAction();
return false;
}
}

Categories