How can I use several click events on the same element in JavaScript?
I try to make that when I click on the h3 element it opens its description and then I again click on the element it closes the description.
var p, img, question;
function clickOn(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.setAttribute('class','show-text');
/*img.setAttribute('class','show');*/
}
function clickOff(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.removeAttribute('class','show-text');
/*img.removeAttribute('class','show');*/
}
question = document.getElementsByClassName('question')[0];
question.addEventListener('click', clickOn, false);
question.addEventListener('click', clickOff, false);
Try using toggle for adding and removing class https://www.w3schools.com/howto/howto_js_toggle_class.asp:
var p, img, question;
function clickOn(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.classList.toggle('show-text');
}
question = document.getElementsByClassName('question')[0];
question.addEventListener('click', clickOn, false);
You can declare a global variable
var isTextDisplayed = false;
Then you can call same event listener and open or close the description on basis of the bit. For example
document.getElementById("myBtn").addEventListener("click", function() {
if(!isTextDisplayed) {
//HIDE DESCRIPTION CODE
}
else {
//SHOW DESCRIPTION CODE
}
isTextDisplayed = !isTextDisplayed;
});
Full code:
var isTextDisplayed = false;
var description = document.getElementById("description");
document.getElementById("myBtn").addEventListener("click", function() {
if(!isTextDisplayed) {
description.style.display = 'none';
}
else {
description.style.display = 'block';
}
isTextDisplayed = !isTextDisplayed;
});
<h3 id="myBtn">CLICK TO TOGGLE DESCRIPTION</h3>
<p id="description">
Some dummy text for description goes here in the block
</p>
For demo, see JSFIDDLE CODE
Related
How can I run an event on dynamically added elements, because my click event doesn't work on new elements.
I found some answer in here but all about jQuery so I'm coding with vanilla javascript. So do you have any advice ?
document.querySelectorAll('.galeri-cart').forEach(function (cart) {
cart.addEventListener('click', function () {
// something awesome happening in here
})
});
creating element codes;
success: function () {
let imageData = JSON.parse(this.files[i].xhr.response);
let img = document.createElement('img');
img.setAttribute('src', imageData.url);
img.setAttribute('data-id',imageData.id);
img.setAttribute('alt', imageData.alt);
let subDiv = document.createElement('div');
subDiv.className = "galeri-cart";
subDiv.appendChild(img);
let midDiv = document.createElement('div');
midDiv.className = "col-md-4";
midDiv.appendChild(subDiv);
let div = document.querySelector('.row');
div.insertBefore(midDiv, div.childNodes[0]);
i++
}
Since you are adding the elements to the DOM manually, you can simply attach the event listener after you create the element and before you append it to the DOM, like so:
function galeriClickHandler () {
// something awesome happening in here
}
success: function () {
let imageData = JSON.parse(this.files[i].xhr.response);
let img = document.createElement('img');
img.setAttribute('src', imageData.url);
img.setAttribute('data-id',imageData.id);
img.setAttribute('alt', imageData.alt);
let subDiv = document.createElement('div');
subDiv.className = "galeri-cart";
// add event listener here
subDiv.addEventListener('click', galeriClickHandler);
subDiv.appendChild(img);
let midDiv = document.createElement('div');
midDiv.className = "col-md-4";
midDiv.appendChild(subDiv);
let div = document.querySelector('.row');
div.insertBefore(midDiv, div.childNodes[0]);
i++
}
Alternatively, you can use event delegation on the static parent element and listen for clicks on specific children, like so:
function galeriClickHandler () {
// something awesome happening in here
}
// Get the parent DIV, add click listener...
document.querySelector(".row").addEventListener("click",function(e) {
// e.target was the clicked element
if (e.target && e.target.matches(".galeri-cart")) {
galeriClickHandler();
}
});
Since you didn't give any info on how you're adding the elements, the only direct code solution to give would be one that delegates the event handling to some container element.
var par = document.querySelector("#parent");
var button = document.querySelector("button");
button.addEventListener("click", function() {
par.insertAdjacentHTML("beforeend", `<p class=galeri-cart>cart ${getCarts().length+1}</p>`)
});
par.addEventListener('click', function(event) {
var cart = event.target.closest(".galeri-cart")
if (cart)
cart.textContent += " clicked!"
});
function getCarts() {
return par.querySelectorAll(".galeri-cart");
}
<button>Add Cart</button>
<div id=parent>
<p class=galeri-cart>cart 1</p>
<p class=galeri-cart>cart 2</p>
<p class=galeri-cart>cart 3</p>
</div>
You added your code. You're already adding attributes and properties to the element, so you just do what you're already doing... bind the handler.
Here's a rewrite that makes your code much more concise and readable.
First, create the event handler.
function clickHandler() {
// your handler code
}
Then create the element and bind the handler to it.
success: function() {
let imageData = JSON.parse(this.files[i].xhr.response);
let div = document.querySelector('.row');
div.insertAdjacentHTML("afterbegin", `
<div class="col-md-4">
<div class="galeri=cart">
<img src="${imageData.url}" data-id="${imageData.id}" alt="${imageData.alt}">
</div>
</div>`);
div.firstElementChild
.firstElementChild
.addEventListener("click", clickHandler);
i++;
}
This question already has answers here:
How to add onload event to a div element
(26 answers)
Closed 5 years ago.
For an assignment, I cannot touch the HTML code and am editing an external JS file. I have to refer the code to an existing class and turn that into a button to run a script.
The has to be ran on load to transform an element with a given id into a button that can also run a function on click.
So let's say the we have id="bar",
how do I go about it?
My code doesn't work at all.
document.getElementById("bar").onload = function () { myFunction() };
function myFunction() {
document.getElementById("bar").innerHTML = "<button></button>";
}
Why don't you just execute your script as the DOM is ready? To do so,
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("bar").innerHTML = "<button></button>";
}, false);
You just need a createElement function.
This works:
document.addEventListener("DOMContentLoaded", function(){
var button = document.createElement("button");
button.innerHTML = "This is a button";
// assuming the Div's ID is bar
var div = document.getElementById('bar');
div.appendChild(button);
//the following function will alert a window when the button is clicked
button.addEventListener ("click", function() {
alert("Button was clicked");
});
});
Updated Codepen
I think this is bit tha you needed
var bar = document.getElementById('bar');
window.onload = function() {
var barInner = bar.innerHTML;
bar.innerHTML = '<button>' + barInner + '</button>';
}
bar.onclick = function() {
alert("Hello\nHow are you?");
};
document.getElementById("bar").onload = myFunction();
function myFunction() {
document.getElementById("bar").innerHTML = "<button>Button</button>";
}
There you go!
Not every single HTML element has a load event.
Only some of them are concerned, such as the window, an image... etc
Have a look here on MDN to learn more about this.
Here is a simple snippet resolving all what you mentioned.
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
button = document.createElement("button");
button.textContent = elt.textContent;
button.onclick = callback;
elt.textContent = '';
elt.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div id="bar" style="background: beige; height: 2em">Click me</div>
In the previous snippet, I am appending the button in the element. But if the matter is really to transform it into a button, there we go:
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
container = elt.parentNode,
button = document.createElement("button");
button.id = elt.id; // if you want to keep the id
button.textContent = elt.textContent;
button.onclick = callback;
container.removeChild(elt);
container.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div style="background: #fee; height: 2em">
<div id="bar" style="background: beige; height: 2em">Click me</div>
</div>
I have a scenario where I need to create a div dynamically, so I created on-ready of document. But it should be displayed on-selection. I am facing the issue, that on page load, the empty div is created. So I need to hide that div and should be shown on-select of text.
JavaScript
$(document).ready(function () {
closePopUp();
var replaceDiv = document.createElement('div');
replaceDiv.id = 'rplceTxtDiv';
document.getElementsByTagName('body')[0].appendChild(replaceDiv);
var innerspan = document.createElement('span');
replaceDiv.appendChild(innerspan);
innerspan.innerHTML += '˟';
var innerDiv = document.createElement('div');
replaceDiv.appendChild(innerDiv);
innerspan.addEventListener("click", closePopUp, false);
replaceDiv.addEventListener("click", getSel, false);
var rplceTxtDiv = $('#rplceTxtDiv');
$('#mytextarea').on('select', function (e) {
var txtarea = document.getElementById("mytextarea");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
rplceTxtDiv.offset(getCursorXY(txtarea, start, 20)).show();
rplceTxtDiv.find('div').text('replace with stars');
}).on('input', function () {
if (interval) {
interval = false;
edits.push($(this).val());
if (edits.length > maxHistorySize) edits.shift();
setTimeout(() => interval = true, saveInterval);
}
});
document.onkeydown = undo;
});
Here is my plunker
The issue is shown in below image:
Hide the DIV before appending it to the HTML by
replaceDiv.style.display = "none";
and I recommend showing it after you have updated the text by
replaceDiv.style.display = "block";
Set a CSS class as:
.MyClass {
display: none;
}
and with jQuery:
$('#myDivIDorClass').addClass('MyClass');
just hide all div having class name "yourclass" with hide()
like this on ready
$('div.yourclass').css("display","none");
On click I can hide my div element with display:none but can't get it back with display:inline when button is clicked
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementsById("red").style.display = "inline";
}
Hi your script has typo error.
getElementsById is having Elements instead of Element.
Alway use Console for error messages it will help you alot :).
Cheers !!!
Your script should look like this .
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementById("red").style.display = "inline";
}
Example: display:none to display:inline toggle.
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementById("red").style.display = "inline";
}
#red
{
color:#fff;
background:red;
padding:8px 20px;
}
<div id="red">RED (Click me)</div>
<button id="back">Back</button>
You can always see the errors in the console and figure out the solution.
I would advise you to use a class for styling and also use Element.addEventListener() for the events.
var red = document.getElementById('red')
var back = document.getElementById('back')
red.addEventListener('click', function() {
this.classList.add('hidden')
})
back.addEventListener('click', function() {
red.classList.remove('hidden')
})
https://jsfiddle.net/cnzabf1a/
Documentation on:
addEventListener
classList
If your're using flex using 'inline-flex' may be better:
document.getElementById("red").style.display = "inline-flex";
I am creating a new div on a click of button and inside that onclick function I am adding a click event to newly created div but its not working.
document.getElementById('blah').onclick = function(){
var innerDiv = document.createElement("div");
document.getElementById('container').appendChild(innerDiv);
innerDiv.onclick =createWorkFunction;
}
function createWorkFunction(e){
alert();
}
can anybody quickly help me
Your code is corrct, But you did not set the text of the your div (an empty div can not be clicked by an user), Try this:
document.getElementById('blah').onclick = function(){
var innerDiv = document.createElement("div");
innerDiv.innerHTML = 'This is a div'; // set it's text
document.getElementById('container').appendChild(innerDiv);
innerDiv.onclick = createWorkFunction;
}
function createWorkFunction(e){
alert('this is some text');
}
Also it's better to use addEventListener
(function() {
var oBlah = document.getElementById('blah');
oBlah.addEventListener('click', function() {
var innerDiv = document.createElement("div");
document.getElementById('container').appendChild(innerDiv);
}, false);
innerDiv.addEventListener('click', function() {
alert();
}, false);
})();
This should help.
try this:
innerDiv.setAttribute("onclick","createWorkFunction()")
function createWorkFunction(){
alert("working");
}