Saturday, October 8, 2016

JavaScript Events.


There are three methods in JavaScript in listening and handling events:

  • onload
  • onclick
  • onmouseover
  • onblur
  • onfocus


METHOD 1
<button onclick="alert('Hello, world!');">
    Run Some JavaScript
</button>

METHOD 2 : Use Element Name and Event Name
// element.event = ...
// ex. window.onload 
// ex. namefield.onblur

myelement.onclick = function () {
    // your event handler code
    // ...
};
// The semi-colon because the 
// whole thing is a statement! (Not because of function)


METHOD 3 : Add Event Listener
// Benefit: flexible, one event for multiple listensers, dynamic
// Drawback : different, not portable across browsers

document.addEventListener ('click', myFunction, false);
//                             event , function to run 

document.addEventListener ('click', anotherFunc, false);
// dynamically add and remove listeners on the same event
document.removeEventListener ('click', anotherFunc, false);
// For IE8
// document.attachEvent ('onclick', myFunction);

// Cross-Browser Add Event Helper Methods
function addCrossBrowserEventListener (elementName, eventName,
functionName) {
    // does the addEventListener function exist?
    if (elementName.addEventListener) {
        // yes - use it
        elementName.addEventListener (eventName, functionName, false);
        return true;
    } else {
        // otherwise use attachEvent
        elementName.attachEventListener 
            ("on" + eventName, functionName, false);
        return true;
    }
}
// or use JQuery


Note:
If the line of javascript, <script src="script.js"></script>, is placed in the <head></head> section, use 'window.onload' to activate the function as soon as the page is loading.

// place script.js at end of <body></body>
var myImage = document.getElementById ("mainImage");
myImage.onclick = function() {
    alert ("Image Clicked!");
}

// Place script.js in <head></head>
function prepareEventHandlers () {
    var myImage = document.getElementById ("mainImage");
    myImage.onclick = function() {
        alert ("Image Clicked!");
    }
}

// Use window.onload to make sure the elements exist before 
// javascript function is called
window.onload = function() {
    prepareEventHandlers ();
}
// window.onload should only be used once for each page, 
// the last one stands.


// in html, input email and name:
<p>
   <label for="email">Email:</label>
   <input type="text" value="your email" name = "email" 
        id="email" tabindex="20" />
</p>

// in javascript:
var emailField = document.getelementById("email");

emailField.onfocus = function() {
    if (emailfield.value == "your email") {
        emailField.value = "";
    }
};

emailField.onblur = function() {
    if ( emailField.value == "") {
        emailfield.value = "your email";
    }
}


No comments:

Post a Comment