html button not calling its onclick js function - javascript

Why does this simple alert not work?
HTML:
<button id="mybutton" type="button" onclick="add()">Add</button>
JS:
function add(){
alert("hello???");
}
https://jsfiddle.net/k86mg0aj/

The problem is specific to JSFiddle. You need to change the LOAD TYPE to No wrap - bottom of <body>.
When using onLoad, the function won't become global one, so you can't invoke it directy from HTML. If it is global - like when using no-wrap - it works.

In my opinion the best solution for call a function in current times is to use ES6. You can create for example something like that:
var x = document.querySelector('.class');
x.addEventListener('click', function() {
});
x.addEventListener('click', () => {
});

Related

Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?
<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>
So it would look like this
<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>
The following Javascript code doesn't work though. Why?
<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>
onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.
Both are like "onclick", but it's not the same.
So, if you want to make thing work, do this:
document.getElementById("my_button").onclick = () => window.location.replace('/destination2');
onclick div property need function(callback) not a string
A simple way to do it would be by adding a listener and preventing the default behavior of the event
document
.getElementById('my_button')
.addEventListener('click', function (event) {
event.preventDefault();
window.location.replace('/destination2');
});
working example
element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.
If you want to change the attribute, make use of element.setAttribute("onclick", "...");
element.setAttribute("onclick", "window.location.replace('/destination2');");
Behaves similar to:
element.onclick = function() { window.location.replace('/destination2'); };
Another solution would be using the data-attributes which can be accessed by element.dataset.name.
Example:
<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>
And to change it:
my_button.dataset.path = "/otherPath";

How do I pass parameters into a jQuery.click() function on a <span> tag?

I have used the jQuery.click() function in the past with buttons and have had nothing but success, but I tried to use it to click on a <span> and it doesn't work.
Also I noticed that it automatically executed my function without listening to the click.
Judging how I used it on buttons, this would be the syntax:
<p><span id="example">Click Here</span></p>
$("#example").click(exampleFunction(p1, p2));
But it does not seem to work. Again it just executes it without the click even taking place. I even tried:
$(document).on("click", "#example", exampleFunction(p1, p2));
Still no luck, same results.
I am making a weather app and my goal with this is to toggle the temperature between Fahrenheit and Celsius by clicking on the unit. I made a copy of the code for the app on codepen.io here:
Codepen Weather App
I appreciate the help!
Looks like you should try something like this:
$(document).on("click", "#example", function() {
console.log('Hello World');
});
Using the function() definition alone give me Uncaught SyntaxError: Unexpected token (.
What you're doing is binding an anonymous function to the click. If you were doing this somewhat differently, like MyFunction(), then it would only execute the function.
If you had MyFunction you could still trigger it using click like so:
function MyFunction() {
console.log('Hurra!')
}
$('#example').click(MyFunction)
Notice that I didn't use the parentheses otherwise it will actually run the function instead of binding it.
Try it like this:
$('#example').click(bleepme);
function bleepme(){
alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><span id="example">Click Here</span></p>
Note that the on-click call to the bleepme function does not have parens -- if you put parens there, it will run the function at document.ready, but not upon click.
Example - no parens on click
Example 2 - parens on click
Well you should supply a body to the function :)
$("#example").click(function() {
alert('clicked');
});
I don't think that you really want to pass parameters into into the function. By the time someone is clicking on the temperature to toggle the units, the document.ready function has finished executing. You actually want to read the values for temp and units from the DOM or from local storage. So, you don't need to pass parameters into your function, which should make things a bit easier.
I think you code need to work like this way
$(document).ready(function(){
$('#example').on('click',function(){
// Some of your logic here
});
});

JS code fires on page load instead of waiting for click event

I'm having difficulty with this code. I'm trying to get the JS to execute on a click event however, it is executing when the page loads and also when the user clicks. Any help is much appreciated!
<body>
click me!
</body>
<script type="text/javascript">
window.onload = function () {
document.getElementById('calc').onclick=xfx()
}
xfx = function (){
alert("x");
}
</script>
</body>
You are invoking the function instead of assigning it to the on click event
This should do it:
document.getElementById('calc').onclick = xfx;
The line
document.getElementById('calc').onclick = xfx();
means that you want to assign the onclick to the results of the xfx() call.
You probably want
document.getElementById('calc').onclick = xfx;
which means that you want to assign to onlick the xfx function itself.
I'd use addEventListener to look for the click on your variable; like so:
var clickMe = document.getElementById('calc');
clickMe.addEventListener('click', function () {
alert("hello!");
});
Where your variable is clickMe, defining the id 'calc', and when clicked it triggers the alert.
Here's the fiddle, http://jsfiddle.net/89Nvb/
Should be
function xfx() {
alert("x");
}

onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})

Toggle text with function called with onclick

my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
​
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>

Categories