Javascript removeEventListener doesn't work - javascript

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!

Related

how to show the sub elements text based on div>a like the select>option structure in a drop-down box using original javascript

everyone. I got some problems when I wanna accomplish a drop-down box in a HTML website without using select and option elements, instead of using and elements.
The main function is made up by two parts, the first function is when clicked the first elements in the drop-down box, the hidden parts of list shows up and hide clicked again. The second function is when choose the elements in the hidden list, the text of the elements on the list will replace the first element on the drop-down box.
I have accomplished first function using below codes:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
But when I did the second part, my idea was not clear enough to implement that, I searched if I use select>option elements I could use selectedIndex method to find the index of list, but this is a custom drop-down box formed by div>a structure elements.
I tried to console.log(a_searchListBtn) and show an array from the console, and I could use a_searchListBtn[0~3].text to get the value of B/C/D.
I tried to write codes like below:
a_searchListBtn.onclick = function() {
console.log("Clicked.")
}
But nothing in the console, so, is there anyone could apply some help, thx in advance.
Well you're fetching all the a elements using getElementsByTagName("a"). Now you just need to loop through the results and add a click event listener that will take the innerHTML of that a element and put it into the innerHTML of the ui-search-selected div.
You don't need an index. You can access the clicked element's innerHTML using event.target. See it working in this snippet below:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var uiSearchSelected = document.getElementById("ui-search-selected");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
for (button of a_searchListBtn) {
button.addEventListener("click", replace);
}
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
function replace(event) {
if (!event) return;
uiSearchSelected.innerHTML = event.target.innerHTML
}
<!-- html codes -->
<html>
<body>
<div>
<div id="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I have tried to use this codes to implement this funtion, it works.
// javascript
var par_searchListBtn = document.getElementById("btn_list_parent");
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
// console.log(a_searchListBtn.length);
// console.log(a_searchListBtn);
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
for(var i = 0; i < a_searchListBtn.length; i++){
a_searchListBtn[i].onclick = function () {
par_searchListBtn.innerHTML = this.innerText;
//searchListBtn.style.display = "none";
}
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" id="btn_list_parent" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>

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>

How to print click events in 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>

See if check box is clicked until it is clicked

I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!
originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo
This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

Categories