javascript function called with an onclick attribute on button - javascript

I don't understand why this is not working.
I'm sticking to the reference on w3schools.
Here the code :
HTML:
<button onclick="click()">Test</button>
Javascript:
function click() {
alert("Hello !");
}

It doesn't work because you have configured JSFiddle to wrap the JavaScript in a function and call it onload. This stops your function being a global so it isn't in scope for your intrinsic event handler attribute.
Additionally, after you fix that, the weird scoping rules for intrinsic event attributes (I have no idea where these are documented) means that click is resolved as the button's click property before the scope is searched far enough to find the global click function.
The quick and dirty solution is:
Rename the function to something that doesn't clash with existing property names
Pick a no wrap option from the menu on the left of JSFiddle
The proper solution is to attach your event handlers with JavaScript. This isn't the 1990s and we should avoid using the techniques of that era that fail to separate concerns. Keep your JS in one place and your HTML in another.
<button>Test</button>
<script>
document.querySelector('button').addEventListener('click', click);
function click(evt) {
alert("Hello !");
}
</script>

This code doesn't work because there's already a click native method and shadowing it prevents the normal click event handling. Give it another name and it will work.
A way to see that is to define your button as
<button onclick="console.log(click)">Test</button>

I think you cann't give a function name as click. Change your function name & it should work.

click seems to be reserved.
Try renaming the method: http://jsfiddle.net/qeCE5/1/
function clickMe() {
alert("Hello !");
}

you need to change the function name. 'click' might be a reserved keyword, so it wont recognize when you call it. rename it to other names eg. 'democlick()'. also don't forget to save your code with '.html. extension. please tell me if any issue exists. thanks.

Related

Changed data attribute not recognized in jquery selector

I've the following html structure
<body data-page="first">
<div class="start">Test</div>
</body>
and the following js
$('body[data-page="first"] .start').on('click',function (){
body.attr('data-page','second');
});
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
I would expect, that after the second click on .start, the console would show "Test", but it doesn't...
Can you tell me what I'm doing wrong?
Thanks in advance!
While you have your answer, I don't think the essential point has been made in any of the answers so far, and that is that the binding of an event handler must happen after the target element exists.
When you try to bind an event handler to a particular element in the DOM, the element must exist at the time. If it does not exist, the handler has nothing to bind to, and so the binding fails. If you later create the element, it's too late, unless you re-run the binding statement.
It will soon become second nature to call appropriate event handler binding statements after you create a new element (by modifying the HTML using javascript) that needs a handler.
For instance, in my current project I regularly make AJAX calls to a server to replace blocks of HTML as things happen on the page. Even if some of the new elements are exactly the same as the ones being replaced, they will not inherit any bindings from the replaced elements. Whenever I update the HTML I call a function that contains necessary statements to bind my event handlers to the new copy of the active elements.
Your code would work if you made the following change:
$('body[data-page="first"] .start').on('click',function ()
{
body.attr('data-page','second');
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
})
A couple of other (off-topic, but related) points:
It's possible to bind a handler to an element multiple times. The trick to avoiding this is to include the .off() method in the chain before binding (noting though that .off("click") will unbind all click handlers bound to that element, not just yours) e.g.
$("#mybutton").off("click").click(function(){myHandler()});
"the arrow function doesn’t have its own 'this' value" () so don't use arrow functions in event handlers if you plan to reference any of the element's properties via 'this'. e.g.
$("#mybutton").off("click").click(() => {console.log(${this.id})}); // >> "undefined"
The issue is that the page is rendered with the data-page set to first, and when you click again on it, that part of javascript still see "first", since is not rerendered, so you need a dynamic function, the read all the intereaction with that button, and than check wich value that attribute has. Like this you can make infinite cases, and still go on.
$('body .start').on('click',function (){
const attr = $('body').attr('data-page');
if(attr === 'first') {
$('body').attr('data-page','second');
} else {
console.log('second');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-page="first">
<div class="start">Test</div>
</body>
And if you don't like the fact that is targetting all the "body" wich is weird, becouse you should have only 1 body, you can use an ID to target the right one
PS: is never a good idea to duplicate your function, if you can set everything in a dynamic function, that reads everything, is easier to debug in the feature, and is lighter and more clean to work on
$('body[data-page="first"] .start').click(function (){
var body = $('body[data-page="first"] .start');
body.attr('data-page','second');
});
This method can help :
var timesClicked = 0;
$('.start').on('click',function (){
timesClicked++;
if (timesClicked>1) {
console.log('Test');
}
});

Analyze JS syntax

I am trying to analyze a line of code written by someone else. Specifically I want to find the Javascript code that is called when the below link is clicked....
<a href="#subtabs_and_searchbar"
id="finish_counting"
onclick="$('#finish_counting').click();">
<span>Submit Answer</span>
</a>
But as you can see they do not have the actual Javascript function name inside the onClick event listener. Can you please help me understand what is there?
Also is this syntax pure Javascript or is there something else there? Jquery perhaps?
Specifically I want to find the Javascript code that is called when
the below link is clicked....
Here it is:
onclick=$('#finish_counting').click();
Now, this code might trigger another click event handler which is not shown in your post and presumably looks like this code:
$('#finish_counting').on('click', function(){
//Do some handling
})
UPDATE:
Taking a further look on your code lead me to the conclusion that you're in an infinite loop - the anchor tag and the jQuery code refers to the same ID.
This is actually just calling the method .click(). It is actually triggering a click event. I'm not sure why they'd want to do that, especially in the onclick attribute...but that's what this code does.

why this simple onclick function not working

Why is this simple code not working? Can someone explain it to me?
JSFiddle
I have called the cc() function in onclick attribute.
HTML
<div> hey </div>
<button onclick="cc()"> click me to change color</button>
Javascript
$(document).ready(function () {
function cc() {
$('div').css('color', 'red');
};
});
cc is not a global function.
It is defined with a function declaration, so it is scoped to the function it is defined in.
That function is the anonymous one that you pass to the ready method. (And you do that inside a function that you run onload due to your jQuery configuration).
Globals are (in general) something to be avoided as much as possible, and intrinsic event attributes usually depend on them.
Don't use intrinsic event attributes. Bind your JavaScript event handlers using JavaScript. Since you are using jQuery, use the on method.
$(document).ready(function(){
function cc(){
$('div').css('color','red');
};
$('button').on('click', cc);
});
demo
The code in the onclick attribute only has access to global functions/variables. The function cc is local to the function it is defined in. You'll want to either define it outside of that function (so it is automatically global) or assign it to window.cc to explicitly make it global (I suggest the second option).
You should attach the handler inside the document.ready something like
html
<div> hey <div>
<button id="mybutton"> click me to change color</button>
javaScript
$(document).ready(function(){
//attach the function here
$("#mybutton").click(
function (){
$('div').css('color','red');
}
);
});
DEMO
As said by Quentin, cc isn't a global function.
But also, the function needs to be declared before it is called. So in fiddle, you should wrap the function in head.
Updated demo:http://jsfiddle.net/zWtZ2/3/
CC is a global
I have updated you fiddle with a working example
Html
<div> hey <div>
<button> click me to change color</button>
Javascript
$('button').click(function()
{
$('div').css('color','red');
});
http://jsfiddle.net/zWtZ2/4/
I wouldn't normally do this but I wanted to give you minimal changes to your code. As you are selecting every single button on div.

Error function not defined in javascript

I have a sample code:
<input width="50" type="text" value="" name="application_id" id="text_input">
Test Name
And javascript
function addSelect(id, title) {
document.getElementById('text_input').value = title;
}
When I run code, result error is addSelect is not defined ? demo here , how to fit it ?
Your script has been defined to run onLoad, which means your function is not available in the global scope like you expect. It will be defined in a local scope of some onLoad method (whichever jsFiddle uses). With this setting, I think jsFiddle puts your code into this or something similar to:
window.onload = function () {
// Your code
};
(which is similar to onDomReady option)
This is so you don't have to worry about binding the right event and you can just test your script (making sure the page has loaded).
When you try to call the function, which you expect to be in the global scope, it won't work. Just change the setting on the left to no wrap (head) (or no wrap (body))
http://jsfiddle.net/TmLut/3/
And as mplungjan has pointed out, and I somehow didn't realize at all, when using the onclick of the anchor element, you'd probably want to prevent default behavior of the link (even if it's just to go to "#"), and can be achieved in several ways, but one is:
Text
Although at the same time, one might argue you shouldn't have inline handlers at all, and would want to be binding the event with Javascript completely. Depending on that case, you have options to prevent the default behavior still. In any case, you can still grab ahold of the event object (normalized per browsers...which jQuery does, by the way) and call event.preventDefault(); in the method.
Here its http://jsfiddle.net/TmLut/4/
I changed onload to head on the left side select box

Javascript onFocus . then onClick inside function

I'm trying to make it so when an element gets focus it calls a function which then will take care of all other events - here is my code for now.
<span id="checkbox" class="checkbox" onFocus="cbHover(checkbox)"></span>
<script type="text/javascript">
function cbHover(id) {
if(document.getElementById(id).onClick) {
document.getElementById(id).style.backgroundPositionY = '-63px';
}
}
</script>
Obviously this isn't working :( So is there a way to keep the function running to listen for other events?
Thanks!
When the object is clicked, it is already focused. You can either skip the onFocus and replace it with onClick, or the other way around and remove if(document.getElementById(id).onClick) from the code, because you don't need it.
You are able to use two events: onFocus and onLostFocus. In onFocus event handler you are able to add onClick event to element:
document.getElementById(id).addEventListener('click',function_name,true);
In onLostFocus event handler you are able to remove event
document.getElementById(id).removeEventListener('click',function_name,true)
this is a bad idea even if you did get it to work you run the risk of applying multiple clicks on the same element. your best bet it to just apply the click event on dom ready I typically use jQuery
so if I where doing this in jquery i would do it like this
$(document).ready(function(){
$('.classname').click(function(){
// what to do onclick
});
});
The reason it isnt working is the parameter that is passed, should be enclosed in quotes.
It should be
onFocus="cbHover('checkbox')"
otherwise, javascript treats checkbox as a variable and tries to pass the value of the variable which is null.

Categories