17

Are there ways for me to listen for onblur or onclick events in javascript from an onload function? instead of doing it in the element itself.

<input type="button" id="buttonid" value="click" onclick="func()">

to become something like

function onload() {
      var button = document.getElementById("buttonid");
      button.addEventListener("onclick", function() { alert("alert");});
}

EDIT

<html>

<head>

     <script>

     function onload() {

        var button = document.getElementById("buttonid");

        if(button.addEventListener){
             button.addEventListener("click", function() { alert("alert");});
        } else {
             button.attachEvent("click", function() { alert("alert");});
        };
     };

          window.onload = onload;


     </script>

</head>

<body>

<input type="button" id="buttonid" value="click">


</body>

</html>

UPDATE

 <script type="text/javascript">

 function on_load() {

    var button = document.getElementById("buttonid");

    if(button.addEventListener){
         button.addEventListener("click", function() { alert("alert");});
    } else {
         button.attachEvent("click", function() { alert("alert");});
    };
 };

      window.onload = on_load();


 </script>

simplified.
  • 561
  • 2
  • 5
  • 7
  • 1
    if you mean _window.onload = onload_, then that would work, or something similar. have you tried your example to see what happens? – thescientist Jun 22 '11 at 19:12
  • @thescientist it didn't actually work for me, maybe i have some errors somewhere. – simplified. Jun 22 '11 at 19:17
  • if you look in the error console, you might find an answer. however, it has since been provided - 'click' vs. 'onclick' – thescientist Jun 22 '11 at 19:19
  • @thescientist i have tried changing the onclick to click but it still doesn't work. let me see the error console and see what it says. thanks. – simplified. Jun 22 '11 at 19:22
  • another important note I mentioned, how are you calling onload? I advised assigning it window.onload to make sure the DOM is ready before referencing it in that function. are you doing that? – thescientist Jun 22 '11 at 19:24
  • @thescientist i was actually referring to body onload. attaching the function to it will this work? – simplified. Jun 22 '11 at 19:25
  • @thescientist it seems that i was thrown an error which says too much recursion, this error is new to me, do you know what does it means? – simplified. Jun 22 '11 at 19:26
  • well, if it's not getting a proper reference, the error console will tell you. (undefined error). if there's no problem regardless, it must be something else. what browser are you using? – thescientist Jun 22 '11 at 19:27
  • darn, comments are terrible for code examples... – thescientist Jun 22 '11 at 19:29
  • @thescientist i am trying this out on mozilla firefox. – simplified. Jun 22 '11 at 19:30
  • @thescientist you can post an answer or edit into my question if you wish to. that should work. – simplified. Jun 22 '11 at 19:31
  • i added an answer. see how it works out, and we can continue the discussion there. – thescientist Jun 22 '11 at 19:33
  • you forgot to add type="text/javascript" to the opening script tag – thescientist Jun 22 '11 at 19:51
  • and change function onload -> my_onload and it should work! :) and of course window.onload = my_onload – thescientist Jun 22 '11 at 19:53
  • @simplified: so is it working then? it should be now – thescientist Jun 22 '11 at 20:21
  • @thescientist don't think so, i have run the updated code, but it still doesn't seem to work. – simplified. Jun 22 '11 at 20:22
  • @simplified: Do not use `window.onload`, this will detach all other event listeners. So, all of them will not get fired, if you do it this way. Please take a look at my _Update 2_ for a working example. – Shef Jun 22 '11 at 20:27
  • i got it. based on the MDN link I provided, certain browsers require a third parameter for addEventListener. add true here, button.addEventListener("click", function() { alert("alert");}, true); I checked in FF and now it works! – thescientist Jun 22 '11 at 20:29
  • @thescientist @Shef thanks, both solution works. but according the the MDN link it says the third parameter should be optional. any idea what does the true and false actually means? the explanation there is kinda complicated for a person like me. – simplified. Jun 22 '11 at 20:36
  • @simplified: _[Note that this parameter is not optional in all browser versions. If not specified, useCapture is false](https://developer.mozilla.org/en/DOM/element.addEventListener)_ (that is FF alone), imagine the others. If set to true, it means your event listener will be fired before any other event of the same type below the level of the element that your event is listening to. – Shef Jun 22 '11 at 20:45
  • @Shef so this means the safer way of doing it is to just set it to false? – simplified. Jun 22 '11 at 20:52
  • @simplified: The safer way from what? It's OK (desired?) for your event to get fired before any other event below it on the DOM tree. If set to `true`, it would also prevent your event from getting fired if the event occurred on an inner element. However, in your case there can't be any inner elements. So, set it to `true` or `false`, but don't forget to set it. If I were you, I would set it to `true`. Once again, do NOT use the `window.onload = on_load()` suggested here. It will break too many things. Take a look at my example for the best way to do it. – Shef Jun 22 '11 at 20:58

5 Answers5

18

The way you are doing it is fine, but your event listener for the click event should be like this:

button.addEventListener("click", function() { alert("alert");});

Notice, the click event should be attached with "click", not "onclick".

You can also try doing this the old way:

function onload() {
   var button = document.getElementById("buttonid");
   // add onclick event 
   button.onclick = function() { 
        alert("alert");
   }
}

Update 1

You need to also monitor for IE < 9, because those Vs use attachEvent(). Attach the event like this, so it will work with dinosaur browsers:

if(button.addEventListener){
    button.addEventListener('click', function() { alert("alert");});    
} else if(button.attachEvent){ // IE < 9 :(
    button.attachEvent('onclick', function() { alert("alert");});
}

Update 2

Based on your edit, this should work works just fine.

<html>
    <head>
        <script type="text/javascript">
            function init() {
                var button = document.getElementById("buttonid");
                if(button.addEventListener){
                    button.addEventListener("click", function() { alert("alert");}, false);
                } else if(button.attachEvent){
                    button.attachEvent("onclick", function() { alert("alert");});
                }
            };
            if(window.addEventListener){
                window.addEventListener("load", init, false);
            } else if(window.attachEvent){
                window.attachEvent("onload", init);
            } else{
               document.addEventListener("load", init, false);
            }
        </script>
    </head>
    <body>
        <input type="button" id="buttonid" value="click">
    </body>
</html>

Please, do not use window.onload = on_load();, this will prevent all other onload event listeners from getting fired, or you are risking for your event listener to get overwritten. Consider attaching the onload event the way I am suggesting above.

Shef
  • 44,808
  • 15
  • 79
  • 90
  • thanks for your reply, i tried changing the way i added the event listener, but it still seem to not work. could it be that i have missed something out? – simplified. Jun 22 '11 at 19:20
  • i have tried to replace the whole code with the onload method you provided and also tried replacing the "onclick" to "click" but it still doesn't seem to work. i wasn't able to see any error too, do you happen to know the possible reason why? – simplified. Jun 22 '11 at 19:29
  • @simplified: If by any chance you are checking it in an IE browser version < 9, please check the update. The other reason it might not be working, is because you are not calling the `onload()` function on your `body` tag, like ``. – Shef Jun 22 '11 at 19:30
  • 1
    The "old" way is far more stable than using event listeners. There's nothing wrong with it. Event listeners are handy, but they're unnecessary for basic DOM scripting. –  Jun 22 '11 at 19:47
  • @Matt McDonald: I agree. Indeed, that's what I suggested initially. For something trivial I hook them up often, that's why it was the first thing off the top of my head. :) – Shef Jun 22 '11 at 19:54
2

The better way it's used DOM (works perfectly) like this. Firs write Yours function/class and use it in:

document.addEventListener('DOMContentLoaded', function(){
  // put here code
});
<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    function myFunc(){ alert('Hellow there!'); }
    
    document.addEventListener('DOMContentLoaded', function(){
        document.getElementById('mybtn').addEventListener('click', myFunc);
    });
  </script>
</head>
  <body>
    <button id="mybtn">Cklik!</button>
  </body>
</html>

It's doesn't matter where You used this few lines. You can put it in head or in body.

Jerzy Drożdż
  • 438
  • 6
  • 8
0
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
  var required = document.getElementById("required").value;
  if (required===null || required==="") {
    alert("Please make sure all required field are completed");
  }
  else  {
    alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
  }
});
</script><html>
<body>
<div id="popup">
    <textarea cols="30" rows="2" name="required" id="required"></textarea>
    <input type="submit" id="click" value="Submit">
           <input type="reset" value="Reset" />
</div>
</body>
</html>
0

A better way to dynamically add event handlers would be to use a JavaScript library like jQuery, because it will abstract away any browser-specific details.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
  • @FishBasketGordo thanks for your reply, do you mind explaning the meaning of browser-specific details? – simplified. Jun 22 '11 at 19:18
  • For instance, Firefox uses `addEventListener` to register an event handler (this is the standard approach), but IE uses `attachEvent` to do the same thing. With jQuery, you would call the same function (`bind` or one of its shorthand versions such as `click`) no matter which browser you're using. – FishBasketGordo Jun 22 '11 at 19:27
  • @FishBasketGordo ohh, so does that mean that if i decide to go without the jquery, in order to make the code compatible for most browsers out there, i will have to write a if else to check? – simplified. Jun 22 '11 at 19:32
  • @simplified That's correct. One of the best features of using a framework like jQuery is that most of those annoying browser compatibilty gotchas are handled in the framework, and thus, don't have to be handled in your code. – FishBasketGordo Jun 22 '11 at 19:36
  • @FishBasketGordo thanks. but does it make any sense to forgo the use of the library in order to create something independent? although it does really provide good functions for browser compatibility. – simplified. Jun 22 '11 at 19:41
  • @simplified I don't think that independence would be preferred in this case. jQuery is widely used and has great documentation and a great community (so do other frameworks like Mootools and Dojo, but jQuery is the one I use). – FishBasketGordo Jun 22 '11 at 19:47
  • @FishBasketGordo because the thing is that i will only be using probably 1 or 2 functions that it will provide and will it be redundant to actually include the rest? – simplified. Jun 22 '11 at 19:49
  • @simplified I've heard this concern before. jQuery is very light-weight. The minified jQuery is only 31KB, and if you like, you can link to it on Google's extremely fast servers (http://code.google.com/apis/libraries/devguide.html#jquery). In most cases, it's not going to impact performance noticeably. – FishBasketGordo Jun 22 '11 at 19:53
  • @FishBasketGordo yeah, i have read on that too, there was a specific question asked on it. but i am actually trying to know the different methods of doing it. since, i am not really relying on it to get things working. but still, thanks for the explanation. – simplified. Jun 22 '11 at 19:58
0

to further my conversation in the comments section...

@simplified, try putting this in the < head > of your page

<script type="text/javascript">
function my_onload() {
  var button = document.getElementById("buttonid");
  if(button.addEventListener){
    button.addEventListener("click", function() { alert("alert");}, true);
  }else{
    button.attachEvent("click", function() { alert("alert");});
  };
};
window.onload = my_onload;
</script>

and see what happens. also, please advise us on which browser you are using. https://developer.mozilla.org/en/DOM/element.addEventListener

thescientist
  • 2,906
  • 1
  • 20
  • 15
  • @thescientist i mentioned it in the previous comment section, i am using mozilla firefox. not too sure about the version though. anyway, what does OP means? – simplified. Jun 22 '11 at 19:34
  • @thescientist ohh, so that's what it meant. the thing is that i tried replacing the entire script tag in the head section of the html but it still doesn't seem to work. it still throws the too much recursion error. and i don't know why. – simplified. Jun 22 '11 at 19:39
  • are you sure you only have one element with that ID? can you update your original post with the whole code? Just with barebones markup (just html/head/body tags) the script and then the button element? – thescientist Jun 22 '11 at 19:42
  • @thescientist i have added the entire html code into the question. – simplified. Jun 22 '11 at 19:48
  • @Matt: the onclick was a copy/paste error, but fixed. I'm not sure what other conditions you think may exist besides those two, but I'm pretty confident in following the MDN convention... – thescientist Jun 22 '11 at 19:49
  • @thescientist yeah, i am quite sure that that's the only element with that id, since there's only 1 element in the whole html page. – simplified. Jun 22 '11 at 20:00
  • cool, well I added the solution to your original post. if it works (it should, haha), feel free to accept my answer! ;) – thescientist Jun 22 '11 at 20:01
  • @thescientist i tried making changes to the script tag and my_onload for both the function name and assigning it to window.onload. but it still seem to not work. is there something wrong on my side? – simplified. Jun 22 '11 at 20:10
  • @thescientist i have added the changed code into the question. – simplified. Jun 22 '11 at 20:13