Categories
JavaScript

JavaScript Event Object

Event object stores information about the event happening on a page.

You can get a hold of it in JQuery by using the handle argument that contain it:

$(document).click(function(evt) {
 var xPos = evt.pageX;
 var yPos = evt.pageY;
 alert(‘X: ” + xPos + ‘ Y: ‘ + yPos);
});

In this case, evt holds the event object. This is an arbitrary name, it can be set by the developer to anything.

Some common event properties:

  • pageX – Distance in pixels of the mouse pointer from the left edge of the browser window
  • pageY – Distance in pixels of the mouse pointer from the right edge of the browser window
  • screenX – Distance in pixels of the mouse pointer from the left edge of the monitor
  • screenY – Distance in pixels of the mouse pointer from the right edge of the monitor
  • shiftKey – True if the shift key down when the event occurs
  • which – Use with the keypress event to determine the numeric code of the key pressed
  • target – The target object of the event (example: in click() event, what event was clicked)
  • data – JQuery propietary object used with the bind() function to pass data to an event handling function

To prevent the current event default behavior from happening, you can use the handle and call the preventDefault() method, that is native of the Event Object, or just return false as well:

         evt.preventDefault(); // don’t follow the link

To remove events using JQuery, you can do the following (example):

$('.tabButton').unbind('click'); // For elements with .tabButton class, they won't respond to the click event
When an event is bind to an element, the children of that element also inherit the event binding.
For instance, if you attach an event to a <div> tag, the elements inside will also have it.
To stop this behavior, you can use the function evt.stopPropagation()
Categories
JavaScript

Avoid console.log error messages in IE

Use the following piece of code:

if (typeof console == “undefined” || typeof console.log == “undefined”) var console = { log: function() {} };

Categories
JavaScript

JavaScript global and local variables

Any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope. A local variable can have the same name as a global variable.

Categories
JavaScript

JavaScript looping through objects

Use the following example:

for (prop in google_news.sections) {
    console.log(“result:”,google_news.sections[prop].link);
  }

And the object:

var google_news = {
 sections : {
  ‘0’: {
    link : “this is the first link”,
    contents : “content for first link”
   },
  ‘1’: {
    link : “this is the second link”,
    contents : “content for second link”
   },
  ‘2’: {
    link : “this is the third link”,
    contents : “content for third link”
   },
  ‘3’: {
    link : “this is the four link”,
    contents : “content for four link”
   },
  ‘4’: {
    link : “this is the fifth link”,
    contents : “content for fifth link”
   }
 }
};

Categories
JavaScript

Jquery toggle function

This function respond to click events in an element, calling the functions specified as you click or toggle actions on it:

function showSubmenu() {
  $('#submenu').show();
}
function hideSubmenu() {
  $('#submenu').hide();
}
$('#menu').toggle(showSubmenu, hideSubmenu);
Categories
JavaScript

JQuery onhover function

Example:

function showSubmenu() {
  $('#submenu').show();
}
function hideSubmenu() {
  $('#submenu').hide();
}
$('#menu').hover(showSubmenu, hideSubmenu);
You can also use anonymous functions inside the hover()
Categories
JavaScript

Jquery onload event

Example:

$(document).ready(function() {
  //your code goes here
});

Categories
JavaScript

Javascript event types, and JQuery event handling

Even if multiple events are happening in the DOM, only one is being handle at a time, everything else is put in hold in the mean time, even thing running under setTimeOut for example. This is because javascript is single threaded.

  • Inline events: events embeded in the HTML of the page (see example below), not recommended because you are mixing HTML and JavaScript functionality, and you can only attach one event per DOM element:
<a href="page.html" onmouseover="alert('this is a link');">A link</a>
  • The traditional way: directly assign a function name to a page element (see example below). Note that you can’t use () in the function call, otherwise JavaScript will run the function right away, not at event time. Another disadvantage is that you can only assign one function to one event handler at a time. For instance, window.onload=[my event] where “my event” can only be one function, if specified again, it would overwrite the previous call.
function message() {
  alert("Welcome...");
}
window.onload=message;
  • Event listeners: Same concept as above, but you can assign multiple event listeners per element. The problem here is that IE has its own, propietary way of doing this. All other browsers (Firefox, Safari) use addEventListener(), IE uses attachEvent() for this purpose. removeEventListener and removeEvent are also used to remove events from DOM elements. It is recommended to use a JavaScript library to mask these differences.
  • Here are some of the ways JQuery handle events:
    • $(‘a’).mouseover( ); // Adds a mouseover event to all links in the page
    • $(‘#start’).click(startSlideShow); // Calls function startSlideShow when #start element is clicked
    • $(‘#menu’).mouseover(function() {
      $(‘#submenu’).show();
      }); // Pass an anonymous function to the event handler
Categories
Compatibility issues JavaScript

unload event behavior differences between browsers

Safari and IE fire the unload event whenever you click a link to leave a page or even just close a window or tab with the page. Opera and Firefox let you click the window’s close button without firing the unload event.

Categories
JavaScript

Difference between this and $(this) in JQuery

this refers to the actual DOM element, where stuff like innerHTML, can be used.

$(this) refers to the JQuery wrapper of that element, which where you can use JQuery propietary stuff, like .html()