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>

22
  • 1
    if you mean window.onload = onload, then that would work, or something similar. have you tried your example to see what happens? Commented Jun 22, 2011 at 19:12
  • @thescientist it didn't actually work for me, maybe i have some errors somewhere. Commented Jun 22, 2011 at 19:17
  • if you look in the error console, you might find an answer. however, it has since been provided - 'click' vs. 'onclick' Commented Jun 22, 2011 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. Commented Jun 22, 2011 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? Commented Jun 22, 2011 at 19:24

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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: 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 <body onload="onload()">.
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.
@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. :)
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.

Comments

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.

9 Comments

@FishBasketGordo thanks for your reply, do you mind explaning the meaning of browser-specific details?
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 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 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 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.
|
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

9 Comments

@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?
@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.
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 i have added the entire html code into the question.
@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...
|
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.