javascript: toggle event listener with onclick - javascript

I have this JS function which I'm trying to toggle on and off when clicked on the object with the myFunc() function on it. The trouble I'm having is that by the time the code reaches the first if(myVar)/else part and tries to do the handler it has already switched the myVar variable to false. What should I change to correct my logic error?
<script type="text/javascript">
var myVar = true;
function myFunc(myElement) {
var ele = myElement;
var myHandler = function(event) {
if(myVar) {
// do something
} else {
// do something else
}
}
if(myVar) {
window.addEventListener('mousemove', myHandler, false);
myVar = false;
} else {
window.removeEventListener('mousemove', myHandler, false);
myVar = true;
}
}
</script>
...
<body>
<div id="div1" onclick="myFunc(this)"></div>
</body>

I think this is what you are looking for:
var myVar = false;
function myHandler(event) {
if (myVar) {
console.log('do something');
}
}
function myFunc(myElement) {
var ele = myElement;
myVar = !myVar;
if (myVar) {
window.addEventListener('mousemove', myHandler, false);
} else {
window.removeEventListener('mousemove', myHandler, false);
}
}
<button onclick="myFunc(this)">click me</button>
Tell me if there is something you're not understanding in this code.

Why does myHandler need to check the value of myVar? According to your logic, myVar will always be false when myHandler runs, because you're always setting it to false when you add the event listener. myVar will only ever be set to true when you remove the event listener, so myHandler will never run when myVar is true.
You can remove the if(myVar)/else from myHandler since myVar will always be false there.

you can achieve this by 2 methods
method 1:
<body>
<div id="div1">div</div>
</body>
<script type="text/javascript">
var myVar = false;
var myHandler = function() {
myVar = !myVar;
}
document.getElementById('div1').addEventListener('click', myHandler);
</script>
method2:
<body>
<div onClick="myHandler()">div</div>
</body>
<script type="text/javascript">
var myVar = false;
var myHandler = function() {
myVar = !myVar;
}
</script>
hope you have found what you are looking for.

Related

How to call a function which is inside another function's if statement

I am trying to run this type of code:
Javascript Code:
var a = new XMLHttpRequest();
a.open('GET', 'text.txt');
a.onreadystatechange = function() {
var a_text = a.responseText;
If (a_text == "text I have written."){
document.getElementById("elem").innerHTML= a_text;
function z() {
document.getElementById("elem2").setAttribute("class", "invisible");
};
} else {
alert("Sorry, Text doesn't match.");
};
};
function click() {
z();
//Some other codes
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<style type="text/css" media="all">
.invisible {
display: none;
}
</style>
</head>
<body>
<p id="elem"></p>
<p id="elem2">Click the button to make me invisible.</p>
<button onclick="click()">Click Me</button>
<script src="javascript.js" type="text/javascript"></script>
</body>
</html>
At the last I want that when I click on the button, function click() runs and function z() runs only if a_text matches required text. But even if the text matches, the console shows that z() is not defined.
Please include if you have any alternative code to do it easily.
Help me out please.
This is a part of my code where I need the help. Solving this part will let me complete my project.
z() is not defined.
Because z() declared on inside the ajax callback not as a global.
And also not necessary do like this. You could do with declare as global function. And if you need any special behaviour with in function you could pass with params
Updated
var a_text = '';
function z() {
if(a_text == "text I have written.") {
document.getElementById("elem").innerHTML = a_text;
document.getElementById("elem2").setAttribute("class", "invisible");
} else {
alert("Sorry, Text doesn't match.");
}
};
var a = new XMLHttpRequest();
a.open('GET', 'text.txt');
a.onreadystatechange = function() {
a_text = a.responseText;
}
function click() {
z();
//Some other codes
}
First you need to put z() declaration on the top level so that it can be called from click().
Secondly, you have to create a flag shouldRunZ that will control whether z should run.
function z() {
document.getElementById("elem2").setAttribute("class", "invisible");
};
var shouldRunZ = false;
var a = new XMLHttpRequest();
a.open('GET', 'text.txt');
a.onreadystatechange = function() {
var a_text = a.responseText;
if (a_text == "text I have written.") {
shouldRunZ = true;
document.getElementById("elem").innerHTML = a_text;
} else {
shouldRunZ = false;
alert("Sorry, Text doesn't match.");
};
};
function click() {
shuldRunZ && z();
//Some other codes
}

Function inside event listener triggers only on it's initialization

var init = true;
$('#btn').on('click', delay(function() {
$('#text').append('click');
init = false;
}, 100));
function delay(fn, ms, enabled = true) {
$('#text').append(init);
// if(init) disable delay
let timer = 0;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), ms || 0);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>
Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation.
The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.
For example, try clicking the trigger button. The init variable value is printed only for the first time.
You are calling the delay function in a wrong way in the click handler. You have to call it like so:
$('#btn').on('click', function () {
delay(function() {
$('#text').append('click');
init = false;
}, 100);
});
You will have to check for the value of init inside the function, like this:
$('#btn').on('click', delay(function() {
if(init) {
$('#text').append('click');
init = false;
}
}, 100));
At the moment I don't know why append is not working but with a little workaround you can obtain what you want. Concatenate the original text and the actual one and use text() to set it again:
var init = true;
$('#btn').on('click', function() {
$('#text').text(init);
setTimeout(myDelay, 5000);
});
function myDelay() {
let originalText = $('#text').text();
init = false;
console.log("init is false");
console.log("original text displayed: " + originalText);
$('#text').text(originalText + " " + init);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>

javascript object prototype call

b2 and b3 are not triggering the prototype functions and no errors are generated? How does one accomplish calling prototype functions in the fashion?
<html>
<head>
<script type="text/javascript">
function newObj(){
this.obj_val= 7;
}
var trigger_f0 = function(){
alert("here 0"); // trigger FINE! (ok)
}
newObj.prototype.trigger_f2 = function (){ // no triggering off click event
alert("here 2");
}
newObj.prototype.trigger_f3 = function (){ // not triggering off click event
alert("obj value:" + newObj.obj_val);
}
var init = function(){
b3.addEventListener('click', newObj.trigger_f3, false);
b2.addEventListener('click', newObj.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
}
window.addEventListener('DOMContentLoaded', init, false);
</script>
</head>
<body>
<button id="b1">B1</button>
<button id="b2">B2</button>
<button id="b3">B3</button>
</body>
</html>
You need to create an instance like to get an object out of the constructor function
var a=new newObj()
and then access the properties.
and change newObj.obj_val to
new newObj().obj_val
function newObj() {
this.obj_val = 7;
}
var trigger_f0 = function() {
alert("here 0"); // trigger FINE! (ok)
}
newObj.prototype.trigger_f2 = function() { // no triggering off click event
alert("here 2");
}
newObj.prototype.trigger_f3 = function() { // not triggering off click event
alert("obj value:" + new newObj().obj_val);
}
var a = new newObj();
b3.addEventListener('click', a.trigger_f3, false);
b2.addEventListener('click', a.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
<body>
<button id="b1">B1</button>
<button id="b2">B2</button>
<button id="b3">B3</button>
</body>
When you create a function and add properties to its .prototype, the function doesn't receive them.
Instead, when you create an instance/object using that function as constructor, that object will get the functions.
function foo() {}
foo.prototype.fn = function(){}
var x = new foo()
console.log(foo.fn) // undefined
console.log(x.fn) // function (){}
In your case,
// ...
var obj = newObj();
var init = function(){
b3.addEventListener('click', obj.trigger_f3, false);
b2.addEventListener('click', obj.trigger_f2, false);
b1.addEventListener('click', trigger_f0, false);
}
window.addEventListener('DOMContentLoaded', init, false);

How to unbind document keypress event with anonymous function

This is page's code.
I can't modify this.
var Example = {};
Example.create = function() {
var obj = new Example.object();
return obj;
}
Example.object = function(){
this.initialize = initialize;
function initialize() {
window.addEventListener('load', activate);
}
function activate() {
document.addEventListener('keypress', keyPressed);
}
function keyPressed(e) {
alert("Hello!");
}
};
Example.defaultObject = Example.create();
Example.defaultObject.initialize();
I have tried many things...
document.onkeypress = null;
document.keypress = null;
document.removeEventListener('keypress');
$(document).unbind('keypress');
$(document).off("keypress");
$("*").unbind('keypress');
$(document).bind('keypress', function(e) { e.stopPropagation(); });
but all failed.
How can I unbind event of document keypress?
You have to pass the listener to remove it: (a variable pointing the function aka the function name)
document.removeEventListener('keypress', keyPressed);
https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener
You will have to save it somewhere to remove it later
Root cause of the issue is removeEventListener method. This method expect second parameter which is listener method
document.removeEventListener('keypress', Example.defaultObject.keyPressed);
Here you go for Solution on your problem.
var Example = {};
Example.create = function() {
var obj = new Example.object();
return obj;
}
Example.object = function(){
this.initialize = initialize;
function initialize() {
window.addEventListener('load', activate);
document.getElementById('disable').addEventListener('click', deActivate);
}
function activate() {
document.addEventListener('keypress', keyPressed);
}
function deActivate() {
document.removeEventListener('keypress', keyPressed);
document.querySelector('h1').innerHTML = 'Page Key Press Listener Removed';
}
function keyPressed(e) {
alert("Hello!");
}
};
Example.defaultObject = Example.create();
Example.defaultObject.initialize();
<body>
<h1>Page has Key Press Listener</h1>
<input id="disable" type="button" value="deactivate">
</body>

disable function using javascript

I can not seem to find the code to disable a javascript function. What I want to do is have a javascript function and then I want to disable it. Here is the code:
<script>
var fooFunc = function fooFunction() {
alert("HELLO");
};
$(document).ready(function() {
fooFunc.disable();
});
</script>
<button onclick="fooFunc()">Button</button>
Basically, when the button is click the function should not work, it should be disabled. Thanks
"Disabling" fooFunc is the same as setting it to an empty function (not to null--that will cause an error when it is called the next time). In this case:
$(document).ready(function() {
fooFunc = function() { };
});
But I don't see how this is different from simply removing the onclick handler from the HTML element.
If you want the ability to disable/re-enable the function, you can write it like this:
fooFunc = function() {
function _fooFunc() {
if (!enabled) return;
alert("HELLO");
}
var enabled = true;
_fooFunc.enable = function() { enabled = true; };
_fooFunc.disable = function() { enabled = false; };
return _fooFunc;
}();
If you want to extend this to allow any function to be enabled/disabled, you can write a higher-order function, which takes any function as a parameter, and returns a function with enable and disable methods attached to it:
function disablable(fn) {
function inner() {
if (!enabled) return;
fn();
}
var enabled = true;
inner.enable = function() { enabled = true; };
inner.disable = function() { enabled = false; };
return inner;
}
Now you can define fooFunc as
var fooFunc = disablable(function fooFunction() {
alert("HELLO");
});
and the rest of your code will work as you want.
You can access the onclick property of the element..
<button id="id" onclick="fooFunc()">Button</button>
<script>
document.querySelector('#id').onclick = '';
</script>
If you don't want the function to work at all and be totally disabled then use the below.
If you want the function to work only under certain conditions then you will need if/else statements so it will work only when the conditions that you have set are met.
$(document).ready(function(){
$("button").onclick(function(event){
event.preventDefault();
});
});
You were going to define it back to undefined or null.
fooFunc=undefined;
You Should be doing this :) Change function definition on very first run and you are good to go.
<! DOCTYPE html>
<html lang="en">
<body>
<script>
var fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
var enablefooFunc = function()
{
fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
}
</script>
<button onclick="fooFunc()">Run once and Disable FooFunc</button>
<button onclick="enablefooFunc()">Enable FooFunc</button>
</body>
</html>

Categories

Resources