How to print click events in Javascript - javascript

<body>
<button id ="b1">BUTTON</button>
</br>
<p id="text"> </p>
<script type="text/javascript">
document.getElementById("b1").onmouseout = reset_button;
document.getElementById("b1").onmousedown = mousedown_button;
document.getElementById("b1").onmouseover = mouse_over;
document.getElementById("b1").onmousemove = mouse_move;
document.getElementById("b1").onclick = click_button;
function reset_button() {
document.getElementById("text").innerHTML =
"mouseout";
}
function mousedown_button() {
document.getElementById("text").innerHTML =
"mousedown";
}
function click_button() {
document.getElementById("text").innerHTML =
"click";
}
function mouse_over() {
document.getElementById("text").innerHTML =
"mouseover";
}
function mouse_move() {
document.getElementById("text").innerHTML =
"mousemove";
}
</script>
</body>
I want to print mouseout, mousedown, mouseover, mousemove and onlick when I press button. However, this code I made only prints mouseover, mousedown and mouseout. Can someone explain which part is wrong and how to fix it?

Your text gets overwritten, see console output here:
Update: Simplified code
(kudos to Little Alien)
['mouseout', 'mousedown', 'mouseover', 'mousemove', 'click'].forEach(
ev_name =>b1.addEventListener(ev_name, e => console.log(ev_name)))
<button id="b1">BUTTON</button>

Here is a concise version of what you tried to do. Just 3 lines of code.
['mouseout', 'mousedown', 'mouseover', 'mousemove', 'click'].forEach(
ev_name =>b1.addEventListener(ev_name, e => b1.innerHTML += " " + ev_name))
<button id="b1">click me</button>

mousemove and mouseover events are interfering with each other try removing mousemove event.
<body>
<button id ="b1">BUTTON</button>
</br>
<p id="text"> </p>
<script type="text/javascript">
document.getElementById("b1").onclick = click_button;
document.getElementById("b1").onmouseout = reset_button;
document.getElementById("b1").onmousedown = mousedown_button;
document.getElementById("b1").onmouseover = mouse_over;
function reset_button() {
document.getElementById("text").innerHTML =
"mouseout";
}
function mousedown_button() {
document.getElementById("text").innerHTML =
"mousedown";
}
function click_button() {
document.getElementById("text").innerHTML =
"click";
}
function mouse_over() {
document.getElementById("text").innerHTML =
"mouseover";
}
</script>
</body>

Related

Change text inside a button on each click using javascript?

I need to change text each time I click on button.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("data-text") == button.innerHTML) {
button.innerHTML = button.getAttribute("data-text1");
} else {
button.setAttribute("data-text1", button.innerHTML);
button.innerHTML = button.getAttribute("data-text");
}
},
false
);
<div>
<button id="changeText" data-text="Show" data-text1="Hide">Hide</button>
</div>
I don't understand why this code doesn't work when I try to load page using google chrome. However when I loaded it to codepen it worked
It expects from you certain structure like this one:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText" text="Show" >Hide</button>
</div>
<script>
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("text") == button.innerHTML) {
button.innerHTML = button.getAttribute("text1");
} else {
button.setAttribute("text1", button.innerHTML);
button.innerHTML = button.getAttribute("text");
}
},
false
);
</script>
</body>
</html>
Copy paste it to your file and you'll see that it works.
Please mark it as an answer if it fixes your problem :)
Your code is working, but your approach is not so nice. See the 2 options down below.
let text = {
'Hide': 'Show',
'Show': 'Hide'
}
const click = (event) => {
// option 1, it needs the object above.
// It's good for multiple alternatiosn like color, icon etc
// or multiple states like hide to show, show to sure, sure to really, really to hide.
event.target.innerText = text[event.target.innerText];
// option 2, it's good for one or two alternations.
// event.target.innerText = event.target.innerText == 'Hide' ? 'Show' : 'Hide'
}
document.querySelector('button').addEventListener('click', click);
<button>Show</button>
you can make it more simple by removing the custom attribute and use the button innerHTML only along with enum by using Object.freeze(),it will make the code more readable
const titleEnum = Object.freeze({show: "SHOW", hide: "HIDE"});
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.innerHTML === titleEnum.hide) {
button.innerHTML = titleEnum.show;
} else {
button.innerHTML = titleEnum.hide;
}
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText">HIDE</button>
</div>
</body>
</html>
Use innerText to get the value of an element
const changeBtn = document.getElementById("changeText");
changeBtn.addEventListener("click", ()=>{
if(changeBtn.innerText === "2"){
changeBtn.innerText = "1";
}
else{
changeBtn.innerText= "2";
}
});
<div>
<button id="changeText">1</button>
</div>

Javascript removeEventListener doesn't work

So for a website I have a feature where If you click an image it shows it in a lightbox then on the second click it tracks the mouse movement to move the image. That works fine the problem is on the third click I want to toggle the mouse tracking on and off.
I've posted a simplified version of the code with a button instead of an image
<body>
<div id="myDIV"></p>
<button style="padding: 30px;" id="myBtn">Try it</button>
</div>
<p id="demo"></p>
<script>
document.addEventListener('click', buttonClick);
let scrollon =false;
function buttonClick(event) {
var elem = event.target,
elemID = elem.getAttribute('id'),
myBtn = document.getElementById('myBtn');
if (elemID == 'myBtn' && !scrollon){
event.preventDefault();
scrollon=true;
mine();
console.log('triggered')
}else
if (elemID == 'myBtn' && scrollon){
event.preventDefault();
scrollon=false;
mine();
console.log('untriggered')
}
}
function mine(){
if (scrollon == false){
myBtn.removeEventListener('mousemove',scroll);
return;
}
myBtn.addEventListener('mousemove',scroll);
function scroll(e){
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
}
}
</script>
This is a very good alternative code which works perfectly fine and is used very often.
So I only changed the mine() function.
function mine() {
if (scrollon == false) {
myBtn.onmousemove = null;
} else {
myBtn.onmousemove = function (e) {
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
};
}
}
Hope I could help!

Is it possible to alter innerHTML/textContent back and forth (endlessly)?

So i'm thinking to changing innerHTML of <p>Click</p> from content of "Click" into "Clicked" and when being clicked again it changes back again to "Click" (and could be clicked back again to result "Clicked" for endless times).
Can someone give clue? *I appreciate,
This is my fail attempt so far -->
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
let goo = document.querySelector("#event_01");
let clickOnce = function() {goo.innerHTML = "Clicked"};
let clickBack = function(){
goo.innerHTML = "Click"};
if(goo.textContent == "Click") {
goo.addEventListener("click", clickOnce);
} else if (goo.textContent == "Clicked") {
goo.addEventListener("click", clickBack);
}
</script>
</body>
You should put your condition inside a click handler instead of outside. What's between the script tag will only execute once. When the code runs (on page load) the content of goo is Click, so only the listener that sets the content to "clicked" ever gets attached to the element. instead you should do somthing like this:
let goo = document.querySelector("#event_01");
let onClick = function() {
if(goo.textContent == "Click"){
goo.innerHTML = "Clicked";
} else {
goo.innerHTML = "Click";
}
};
goo.addEventListener("click", clickOnce);
You just need to check the value of the .innerHTML of the <p></p>, compare it to the current .innerHTML and change it accordingly
<!DOCTYPE html>
<body>
<p id="event_01" onClick="myFunction()">Click</p>
<script>
function myFunction() {
var x = document.getElementById("event_01");
if (x.innerHTML === "Click") {
x.innerHTML = "Clicked";
} else {
x.innerHTML = "Click";
}
}
</script>
</body>
You just need one listener, attached from the beginning:
let goo = document.querySelector("#event_01");
goo.addEventListener("click", clickListener);
let clickListener = function() {
if (goo.innerHTML == "<p>Click</p>")
goo.innerHTML = "<p>Clicked</p>";
else
goo.innerHTML = "<p>Click</p>";
}
This is simple. your adding to much code.
first of when the p is clicked you assign a click event to clickOnce but in clickOnce
back you never assign clickBack.
Here is an example about what you want to do.
let goo = document.querySelector("#event_01");
let clickMe = function() {
if(goo.textContent == "Click")
{
goo.innerHTML = "Clicked";
}
else
{
goo.innerHTML = "Click";
}
}
goo.addEventListener("click", clickMe);
<p id="event_01">Click</p>
If you don't want to use functions or variables, you can use e.target.textContent
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
document.querySelector("#event_01").addEventListener('click', (e) => {
if (e.target.textContent === 'Click') {
e.target.textContent = 'Clicked'
} else if (e.target.textContent === 'Clicked') {
e.target.textContent = 'Click'
}
})
</script>
</body>

Excluding an area of the DOM on addEventListener

I would like to have an event to trigger when clicking on a box, and a different one when clicking on anyplace less that box. Here's the code:
<body>
<p id="demo"></p>
<script>
document.querySelector("#demo").addEventListener("mouseover", funcion);
document.querySelector("#demo").addEventListener("click", funcion2);
document.querySelector("#demo").addEventListener("mouseout", funcion3);
document.body.querySelector("#demo").addEventListener("click", funcion4, false);
function funcion() {
document.getElementById("demo").innerHTML += "Mouse encima!<br>";
}
function funcion2() {
document.getElementById("demo").innerHTML += "Click dentro<br>";
}
function funcion3() {
document.getElementById("demo").innerHTML += "Mouse fuera!<br>";
}
function funcion4() {
document.getElementById("demo").innerHTML += "Click fuera<br>";
}
document.querySelector("#demo").addEventListener("click", function(e) {e.stopPropagation();}, true);
</script>
</body>
"Tecnically" that should solve it, though i am getting the reverse solution I am looking for, it triggers both events (in & out) when clicking over the box, and none of the events when clicking out of it. I'm out of ideas.
You can add an event listener to the document itself and detect the real target of the event from there.
var box = document.getElementById('demo');
document.addEventListener('click', function(e) {
if (e.target === box) {
console.log('Clicking on the box');
} else {
console.log('Clicking outside of the box');
}
});
<p id="demo">This is the box!</p>

How to show/hide a div in javascript?

When i click the button i want the div to show, and when i click the button again i want it to disappear. What am i doing wrong?
<button type="button" onclick="myFunction()">Click Me!</button>
<div id="Dglow" class="Dglow">
Glow
</div>
<script>
function myFunction() {
var e = document.getElementById("Dglow").style.display;
if (e == "none")
e = "block";
else {
e = "none";
}
}
You should compare and change element's display property:
function myFunction() {
var e = document.getElementById("Dglow").style;
if (e.display == "none") {
e.display = "block";
} else {
e.display = "none";
}
}
<button type="button" onclick="myFunction()">Click Me!</button>
<div id="Dglow" class="Dglow">Glow</div>
Actually document.getElementById("Dglow").style.display returns a string and according to Left hand assignment rule you cannot store anything to that string, since that string is not a variable/object now ie not a reference to DOM anymore
You can do is
var e = document.getElementById("Dglow").style;
if(e.display == "none")
e.display = "block";
else{
e.display = "none";
}
Have you considered using Jquery? If so heres what you need.
$(document).ready(function(){
$("#button").click(function(){
$("#Dglow").toggle();
});
});
You would need to give your button an id for this though.

Categories