Tag Archives: DOM events

Wanted – onfocus/onblur. Why They Don’t Work Always!

On Focus

onfocus

Perhaps you think of onfocus and onblur events as a default behavior existing in any web page. This is not quite true! Onfocurs and onblur are well known in web developing (js) and are fired, of course, when the user tries to point something or leaves some element. Onfocurs is fired when the user either goes to an element with the Tab button on with the mouse. When the element is on focus, evidently, the onfocus event is fired. Actually you can see which element is on focus, like an anchor or input, when the element is outlined by the browser by default. In the same scenario, when some element has been on focus and than the user switches to another element, the onblur event is fired. Thus you may guess that this element is no longer on focus. Continue reading Wanted – onfocus/onblur. Why They Don’t Work Always!

Prevent link default action when mousedown and mouseup fires!

What is preventing default?

I’m sure you know how to prevent the default action of a link when onclick event is attached to it. Yes, it is a common task and by simply adding a return false; at the end of the method called on click it simply doesn’t call the refresh the page. This is really an everyday task. To describe it first, let’s imagine there’s a link with # href value:

<a onclick="”myFunc()”" href="”#”">click here</a>

Than the definition of myFunc() is something like that:

function myFunc() {
   ...
   return false;
}

If that “return false” part was missing you simply get additional # in the uri of the page and worse – you may be scrolled to the top of the page, because of the lack of an anchor with empty name.

OK, but we know how to deal it! But what happens when you don’t attach click event but mousedown/mouseup pair? It may seem the same thing but it is not!

When you place return false on both event handlers of the mousedown/up events nothing happens, there is a # on the end of the uri and yes the document is scrolled.

How the prevent the default action?

Simply by adding onclick event! We already know that this is working and prevents the default action. Just do the following:

$(‘#element_id’).mousedown(function(){
    ...
    return false;
});
$(#element_id’).mouseup(function() {
   ...
   return false;
});

// this doesn’t work like preventing the default refresh
// action until ....
$(‘#element_id’).click(function() {
   return false;
});
// is added