I've created a function search with an event listener on a button. The problem is that the removeEventListener isn't working because init() is inside it to execute. Thus the EventListener is replicated everytime I click the button. If I remove init() all is fine. Maybe i misunderstand someting about it?
Also if i remove the function search and only use const I know it fires ones. But the whole point is that i need to use search.
function search(data) {
const clickHandler = () => {
console.log('search');
init();
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
}
search(data);
function init() {
console.log('hello');
}
console results:
first time; hello
second time; hello hello
third time; hello hello hello hello
The problem here is scoping. When you put the function inside another, it is scoped to that function. So next time you call the function, you create a new function. So you are trying to remove a function that did not exist before.
function clickHandler2() {
console.log('world');
}
function search() {
const clickHandler = () => {
console.log('hello');
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
document.getElementById('search').removeEventListener('click', clickHandler2);
document.getElementById('search').addEventListener('click', clickHandler2);
}
search();
search();
search();
<button type="button" id="search">Search</button>
Related
I have two functions, functionOne() and functionTwo().
How can I go about calling functionTwo() 10 seconds after functionOne() ends/is called?
I'd like functionOne to occur after a button is clicked, and then functionTwo 10 seconds after functionOne ends (without the need to click a button again/have the user do anything!)!
See below for my code!
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
}
functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
I tried to use setTimeout, but the problem is that I don't think there is an 'onend' event I can use for the first function. Eg:
setTimeout(functionOne.onend, 10,000);
This code calls functionOne onClick and calls functionTwo 10 seconds later.
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
function functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
setTimeout(() => functionTwo(), 10000);
}
function functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
Most importantly you have to declare your functions properly using the function keyword: function functionOne, function functionTwo.
Here's the documentation for setTimeout: "The global setTimeout() method sets a timer which executes a function... once the timer expires." So you pass in the function that you want to execute once the timer has completed.
And here are some more methods of approaching the problem.
Cache your paragraph element along with the button up front so you're making the code as DRY as possible.
Move the inline JS to the script, and use addEventListner to the para element
Use textContent instead of innerHTML because you're not adding HTML
// Cache the elements
const para = document.querySelector('#paragraphChange');
const button = document.querySelector('#clickToChangeText');
// Add a listener to the button
button.addEventListener('click', functionOne, false);
// Set the text content of the para element
// and then call the second function with a time out
function functionOne() {
para.textContent = 'Bye World';
setTimeout(functionTwo, 5000);
}
// Update the para with new text
function functionTwo() {
para.textContent = 'Jokes I\'m still here';
}
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText">Click!</button>
Define functionTow() first.
function functionTwo() {
//code to be execute
}
The call functionTwo in functionOne's body using setTimeout.
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}
I don't think there anything called onend in JavaScript you have to use setTimeout(functionTwo, 10000) at the end of functionOne() like this:
function functionTwo() {
//code to be execute
}
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}
How to make this jquery code fire the function itself instead of binding to a button to fire the function?
self.ShowWindow= { observable: ko.observable(false) };
self.OnToggleShowWindow = (it) => () => it.observable(!it.observable());
$('#showWindowButton').click(self.OnToggleShowWindow (self.ShowWindow));
Right now I have to create a button and bind it with my code to be able to trigger a function in my react component. What I'm wondering is that, is it possible to just trigger the function without halving to trigger the jquery click?
My ViewModel in the javascript component.
$ViewModel = function (element) {
var self = this;
self.ShowWindow= { observable: ko.observable(false) };
self.OnToggleShowWindow = (it) => () => it.observable(!it.observable());
self.OnToggleShowWindow (self.ShowWindow);
$(document).ready(function () {
self.OnToggleShowWindow(self.ShowWindow)
};
self.ShowDialog = function (componentId, componentName) {
// The fucntion OnToggleShowWindow is supposed to be called here
};
}
Only outside the ShowDialog function is bound at rendering the page. After what the showdialog is just a function that updates on the already bounded observables.
In my react component I have subscribed to the function, which I now try to retrieve:
this.props.toggleShowWindow.observable.subscribe(this.onToggleShowWindow);
Put () after it instead of passing it to click.
$('#showWindowButton').click(self.OnToggleShowWindow (self.ShowWindow));
becomes:
self.OnToggleShowWindow(self.ShowWindow)()
Don't forget the () after it. Pay close attention to the above line of code and make sure you don't miss any () out.
I wand to call a jquery click function using JavaScript
<input type='button' class="button" value='+Add' id='addImage'>
when i click this button the following function will run
$("#addImage").click(function () {
//my code.....
}
but i need to call this function using another JavaScript function like fn_name()
You can use trigger and the name of the event, like so (the example below uses a self-executing function for simplicity):
$("#addImage").click(function() {
alert('Clicked')
});
(function(){
$("#addImage").trigger('click')
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' class="button" value='+Add' id='addImage'>
use trigger
$("#addImage").trigger("click")
you have this ugly way too, but not recommended:
https://jsfiddle.net/96oxhwsf/
function fn_name() {
$("#addImage").click(function() {
alert('test')
});
}
fn_name()
beatiful way:
function fn_name(elID) {
let btn = document.getElementById(elID);
btn.addEventListener('click', function() {
alert('Test');
}, false)
}
// still need call the function
fn_name('addImage');
even better:
var addImg = () => {
let btnAdd = document.getElementById('addImage')
btnAdd.addEventListener('click', () => {
alert('test')
}, false)
}
declare function
bind click event
call function
//declare
function test(){
//my code.....
}
function callTest(){
// call function
test();
}
function callAClick(){
//trigger
$("#addImage").trigger('click')
}
// bind click
$("#addImage").click(test);
This onClick function does not run the console.log in the code snippet below, any ideas?
var clickFunction = function myfunc() {
return function (){
return console.log('here');
}
};
<button onClick="clickFunction()"> Click here</button>
Thanks for your time
Because you're calling a function that returns a function. If you want to run the function that is returned you would need to do: clickFunction()()
i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
index.html
script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
i want to separate my code into 3 section (similiar with example1)
the view(html element)
the element have which listener
the function
what should i do? or can i do this?
(i don't want to use another library)
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}