Why does the onclick fire next function not assigned to it? - javascript

Why clicking the button fires the alert? It is assigned to the paragraph, not button.
HTML:
<button onclick="foo()">Click me</button>
<p id="hidden" style="display:none"> I was hidden </p>
Javascript:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick();
}
function innnerClick(){
alert("Ouch! That hurt!")
}

Because of this line:
// ----------------------------------------------------vv
document.getElementById("hidden").onclick = innnerClick();
Here you call the innnerClick function immediately.
Just remove () after to pass the reference to a function instead of calling it, i.e.
document.getElementById("hidden").onclick = innnerClick;

Since, you need to add the reference of the function like this:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick;
}
not directly calling it.
Fiddle Demo
In jQuery, we can reproduce the same issue like:
$('button').click(function () {
$('#hidden').show();
$('#hidden').click(innnerClick()); <-- see the function with () here
});
Fiddle Demo
The issue is same here, we just need to pass the function reference to click handler here like:-
$('#hidden').click(innnerClick);
Fiddle Demo

Related

Function is not accessible after onload event. "TypeError: {someFunctionName} is not a function"

I have written a small and simple slider with Javascript. Because I want to be sure that the slider works when I load the javascript in the footer of the page. I added an onload event and copied the whole slider application inside the event. In the HTML I unfortunately have an inline onclick element in a tag. But since I have the code inside the onload scope the onclick doesn't work anymore. My idea is not to bind the event inline in the html but directly in the javascript. That should work. But I am also interested if it is possible to do it with the inline onclick.
Question What do I have to do so that the onclick element addresses the corresponding function within the onclick function?
document.querySelector('body').onload = function() {
function init() {
// ...
}
const f2 = function() {
// ...
}
init();
/* that will work */
const anchorPrev = document.querySelector('.prev');
anchorPrev.addEventListener('click', () => {
console.log('prev');
});
/* My question */
function next() {
console.log('next')
}
};
a {
cursor: pointer;
}
<body>
<a class="next" onclick="next()">next (I'm curious to know if it works!?)</a><br/>
<a class="prev">prev (Will work)</a>
</body>
Two issues:
It's better to wait for the DOMContentLoaded event on the window object.
You're defining the function within the scope of the function, so it's not globally accessible. This means that the onclick can't see the function. Use a let variable, then set the function inside the listener callback like this:
<button onclick="log()">click me</button>
<script>
let log;
window.addEventListener('DOMContentLoaded', () => {
console.log('loaded');
log = () => console.log('clicked');
});
</script>
You can add that the onload event = function next()
JavaSript code:
document.querySelector('body').onload = function() {
const a = document.querySelector('a')
a.onclick = function next() {
event.preventDefault()
console.log('next')
}
};

My function is being run before a button is clicked [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 4 years ago.
In the code below, why does the header text change on page load, and not only after the button is clicked?
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = change_text("header", "something")
</script>
If you wanted to reuse that function and keep the onclick out of the markup, you could do this:
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = function () {
change_text("header", "something");
}
</script>
This uses something called an anonymous function.
Learn more here: JavaScript Functions
The issue is this line:
button1.onclick = change_text("header", "something")
The JS engine will do the following in this order:
Call change_text with the arguments "header" and "something"
Assign the result of change_text (in this case, undefined) to button1.onclick
Jane Doe's answer should work. If you want to keep your current code structure, then you could use the following:
button1.onclick = function(){
change_text("header", "something");
};
This creates an anonymous function and assigns it to onclick. When onclick is triggered, it will execute the function which calls change_text.
Can you try:
<h1 id="header">This is a header</h1>
<button onclick="change_text('header', 'something')" id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
</script>
I am pretty confident that will work as intended for you..
The reason is simple: you have already called change_text("header", "something") in your code. You are basically doing the same thing as:
let res = change_text("header", "something") // already called, res is undefined
button1.onclick = res
If you are actually passing an event handler, it should looks like button1.onclick = change_text, with change_text() taking an event as param instead. OR as seen in the other answer, <button onclick="change_text('header', 'something')" id="btn1">Change text</button> (this creates an anonymous function that would be called on click event)

Does other functions inside the one which is attached using addEventListener also get attached?

I have this function in js:
function one(){
function two() {};
function three() {};
element2.onclick = function {
alert("alert");
}
}
element1.addEventListener("click", one, false)
Along with element1, does the code above listens for the event on element2 all the time as well?
Please check here through 1st button I'm initialize the 2nd button click event using addEventListener(). Run the code then click 1st button after that click 2nd button you'll get alert.
<button id="myBtn1">Button1</button>
<button id="myBtn2">Button2</button>
<script>
function one(){
function two() {};
function three() {};
document.getElementById("myBtn2").onclick = function() {
alert("alert");
}
}
document.getElementById("myBtn1").addEventListener("click", one,false)
</script>
The two() and three() functions are never called. The code that they contain is never executed.
Every time when the element2 is clicked, it'll assigned to a handler and that's a lot of repetition.

Execute a function when pressing a button in jQuery

I am quite new to programming, and have met a problem.
I really want to run this function, when I press a button. Here is the function that I want to run:
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
Alright, I want to run this function, when pressing a button, and here is the code for my jQuery button:
$(document).ready(function(){
$('button').click(function() {
//run function here
});
});
It doesn't have to be jQuery, I just thought that would be easier. I would be very grateful if somebody would help and explain.
Thanks in advance.
Inside your HTML, you can use the onclick event handler to call a function when the button is clicked, using vanilla javascript. Like so:
<button onclick="generateTip()">button text</button>
If you want a solution using jQuery and your current code, all you have to do is call the generateTip() function inside the $('button').click wrapper:
$(document).ready(function(){
$('button').click(function() {
generateTip();
});
});
So if you have a .js file with this code:
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
You can then attach it to an HTML element like so:
<button onclick="generateTip()"> Button </button>
Hope that helps
You're already there?
JQUERY Script:
<script>
$(document).ready(function(){
$('button').click(function() {
generateTip();
});
});
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
</script>
or by onclick only in the actual HTML and a script above:
<script>
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
</script>
Then in your HTML something like this
<input type="button" name"button" onclick="generateTip()";
To execute the function generateTip() on click, put this in your button code:
<input type="button" name="any" onclick="generateTip()"/>

Calling Javascript function from a div

Can I please have some help to call a function that is created in Javascript when a reference is made to a DIV in HTML.
Here is my function:
function testFunction()
{
alert("Test");
}
I would like the testFunction to be called when the following reference is made in HTML:
<div id="testFunction">
Can I please have some help to do this?
You can attach the call to a click handler:
In markup:
<div id="testFunction" onclick="testFunction()">
Or inside your script block:
function testFunction() {
alert("Test");
}
var el = document.getElementById("testFunction");
el.onclick = testFunction;

Categories