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.
Related
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 :-)
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I am working on a javascript file and have code like following
class test(){
constructor(){
}
showBox(){
var countBlock = document.createElement("div");
document.body.appendChild(countBlock);
countBlock.addEventListener('click', function(){
this.showList()
});
}
showList(){
console.log('Element clicked')
}
}
Code is working fine unless I click on element, when I click it shows this.showList() is not a function
Not sure how to resolve it
Use an arrow function:
countBlock.addEventListener('click', () => this.showList());
Arrow functions lexically bind their context so this refers to the original context, which is the context of the code that contains the arrow function.
Or use a regular function but bind the enclosing this to your function:
countBlock.addEventListener('click', function () { this.showList() }.bind(this));
// or shorter, no need to wrap it in a function:
countBlock.addEventListener('click', this.showList.bind(this));
You can read more about this here.
Here is an example based on your code:
class Test {
showBox() {
const countBlock = document.createElement('p');
document.body.appendChild(countBlock);
countBlock.addEventListener('click', () => this.showList());
}
showList() {
console.log('Element clicked')
}
}
new Test().showBox();
p {
width: 20px;
height: 20px;
background: black;
cursor: pointer;
}
class test(){ seems to be wrong, secondly use arrow function to bind this
class Test {
constructor() {}
showBox() {
console.log('Show Box Executed')
var countBlock = document.createElement("div");
let txt = document.createTextNode('Div');
countBlock.appendChild(txt);
document.body.appendChild(countBlock);
countBlock.addEventListener('click', () => {
this.showList()
});
}
showList() {
console.log('Element clicked')
}
}
let _t = new Test();
_t.showBox();
this.showList is outside of the test class's scope because you wrapped it inside an anonymous function.
Do it like this:
class test{
constructor(){
}
showBox(){
var countBlock = document.createElement("div");
document.body.appendChild(countBlock);
countBlock.addEventListener('click', this.showList);
}
showList(){
console.log('Element clicked')
}
}
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.
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 );
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;
}
}