How to Set OnClick attribute with value containing function in ie8? - javascript

My goal is to change the onclick attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3.
For example, this works in Firefox 3, but not IE8. Why?
<p><a id="bar" href="#" onclick="temp()">click me</a></p>
<script>
doIt = function() {
alert('hello world!');
}
foo = document.getElementById("bar");
foo.setAttribute("onclick","javascript:doIt();");
</script>

You don't need to use setAttribute for that - This code works (IE8 also)
<div id="something" >Hello</div>
<script type="text/javascript" >
(function() {
document.getElementById("something").onclick = function() {
alert('hello');
};
})();
</script>

your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}

You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too.
.....

You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);

Related

Jquery Click-handler doesn't work with named function?

I feel like this is one of those problems you only run into after too little sleep or too many coffees...
I have an element
<a id="blah" href="#">somethinghere.com</a>
I define a function
function test(){
alert('hi');
};
I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):
$('#blah').on('click', test());
and load the page, and the handler executes immediately - without any clicks.
However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :
$('#blah').on('click', function(){
alert('hi');
});
it works fine
Doing both (https://jsfiddle.net/8r1rcfuw/39/):
$('#blah').on('click', function(){
test();
});
function test(){
alert('hi');
}
seems to work fine - but seems a little redundant.
This feels like something I've done 1000 times before - what gives?
The event handler has to be a function, and you are passing the result of a function to it:
$('#blah').on('click', test());
is the same as:
$('#blah').on('click', undefined); //As your funcion doesn't return anything
Think of it as a function is a value, you can do:
var myFunction = function() {
alert("Hi");
}
or
function myFunction() {
alert("hi");
}
And then:
$('#blah').on('click', myFunction); //Without invocation!
or using an anonymous function:
$('#blah').on('click', function() {
alert("Hi");
});
You can also use object of function :
var temp=function test() {
alert('hi');
}
$('#blah').on('click', temp);
Try :
$('#blah').on('click', test); // your function name only
Updated Fiddle

Have the element who call my js function

I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}

Appending existing onClick value

I am using javascript and need to grab the value of an existing onclick and append to it. I am not trying to replace the current onclick, I am trying to append to the front, or end, of it. But all different iterations of this effort are failing.
Quick example:
<pre>
<a href="blah" id="tabA" onclick="alert("this");"
<script>
function test() {
alert("that") ;
}
document.getElementById('tabA').onclick = "test();" + document.getElementById('tabA').getAttribute('onclick') ;
</script>
</pre>
When using the .onclick event you should use function and then the action:
document.getElementById("tabA").onclick = function()
{
alert("hello world")//this will work
}
document.getElementById('tabA').onclick = "test();" + document.getElementById('tabA').getAttribute('onclick') ;//fail since events are not variables to store values.
So, what you whatever you are tring to do, in that way it wont work.
I don't know if I had got your point.
My solution is
tabA
<script>
function test() {
alert("that") ;
}
var oldClick = document.getElementById('tabA').getAttribute('onclick') ;
var newClick = function(){
test();
eval(oldClick);
}
document.getElementById('tabA').onclick = newClick;
</script>
when I click the 'tabA', it alerts 'that' then 'this'.
http://jsfiddle.net/x3Xds/
I know this is quite old but, I needed to do the same thing.
I got around this by using an event;
obj.addEventListener('click', function(){ test(); }, false);

Add more behavior to existing onclick attribute in javascript

how can i add more behaviour to existing onclick events e.g.
if the existing object looks like
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
</script>
how can i add more behavior to the onclick that would do also the following
alert("say hello again");
sayGoodMorning()
Best Regards,
Keshav
Here's the dirtiest way :)
<a href=".." onclick='sayHello();alert("say hello again");sayGoodMorning()'>.</a>
Here's a somewhat saner version. Wrap everything into a function:
..
JavaScript:
function sayItAll() {
sayHello();
alert("say hello again");
sayGoodMorning();
}
And here's the proper way to do it. Use the event registration model instead of relying on the onclick attribute or property.
<a id="linkId" href="...">some link</a>
JavaScript:
var link = document.getElementById("linkId");
addEvent(link, "click", sayHello);
addEvent(link, "click", function() {
alert("say hello again");
});
addEvent(link, "click", sayGoodMorning);
A cross-browser implementation of the addEvent function is given below (from scottandrew.com):
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be attached");
}
}
Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.
var link = document.getElementById("linkId");
addEvent(link, "click", function() {
sayHello();
alert("say hello again");
sayGoodMorning();
});
Another way not mentioned is to capture the function currently assigned to the element.onclick attribute, then assign a new function that wraps the old one. A simple implementation to demonstrate would be something like
function addEvent(element, type, fn) {
var old = element['on' + type] || function() {};
element['on' + type] = function () { old(); fn(); };
}
var a = document.getElementById('a');
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
addEvent(a, 'click', sayHello);
addEvent(a, 'click', sayGoodMorning);
Working Demo here
One way would be to write a third function:
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
function foo() {
alert("say hello again");
sayGoodMorning();
}
</script>
link
would also work
Assuming a slight change to your code:
link
In plain ol' JavaScript, you'd do something like this.
var a = document.getElementById('a1');
a.onclick = function () { alert('say hello again'); a.onclick(); }
It's worth noting that jQuery makes this a bit easier. See the documentation on the click, bind, and one, for example, and in general the section on event handler attachment.

I can't get my JavaScript eventlistener to work properly

This has got me stumped, I've tried lots of different things, but I can't get this to work.
Can anyone help? No matter what I try I can't get the click eventlistener on the link to fire. The code is in a greasemonkey script. I believe I have to use the closure method to be able to refer to the function dropit in the greasemonkey script, as it is not available to the code on the page.
dropit = function (e) {
e.preventDefault();
alert(e.target.textContent);
}
document.getElementById('newlink').addEventListener('click',
function (e){
return function (){
dropit(e);
}
}(),false);
You have to have your Greasemonkey script write the code into a new <script> tag in the page. Once that's done, then your in-page event handler setup can proceed as normally. At least, that's the only way I've ever known to do it.
<a id='mylink' href='http://www.google.com'>google</a> the link
<script src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function(Y){
Y.one('#mylink').on('click', function(e){
e.halt();
alert(this.get('href'));
});
});
</script>
here is the non YUI version
<a id='mylink' href='#'>google</a> the link
<script>
(function(){
var dropit = function (e) {
e.preventDefault();
alert(e.target.textContent);
}
document.getElementById('mylink').addEventListener('click', dropit, false);
}());
</script>
e must be passed into second function inside addEventListener, not first.
Like this:
dropit = function (e) {
e.preventDefault();
alert(e.target.textContent);
}
document.getElementById('newlink').addEventListener('click',
function (e){
return function (e){
dropit(e);
}
}(e),false);

Categories

Resources