javascriptunobtrusive-javascriptaddeventlistener

Javascript: Page reloads with eventListener click


In trying to understand javascript best practices, I'm attempting to recreate a piece of inline javascript by adding an event listener from an external javascript file.

The inline code works fine and looks like this:

<p id="inline" align="left">
    This is a body paragraph which changes alignment 
    when a user clicks on a link below
</p>
<p>
    <a href="" onclick="document.getElementById('inline').setAttribute('align', 'right'); return false;">Align Right</a>
</p>

Concerning my problem, the important thing to note here is that return false; prevents the page from reloading (I'm not actually sure why, and wouldn't mind finding out, especially if it relates to the solution to my problem...). This is what I want. I don't need the page to reload to move the text to the right.

However, I have no idea what the best way to keep the page from reloading is when my javascript is in an external file. Here's what my first attempt looks like. I started with html that looks like this:

<p id="external" align="left">
This is a body paragraph which changes alignment 
when a user clicks on a link below. It uses an
external .js file.
</p>
<p>
<a href="" id="aRight">Align Right</a>
</p>

And javascript that looks like this:

function alignListener () {
    document.getElementById('external').setAttribute('align', 'right');
}
function installListeners () {
    var aRight = document.getElementById('aRight');
    aright.addEventListener('click', alignListener, false);
}

This almost works, but not at all how I would expect. When I click on the 'Align Right' link, the text briefly aligns right, but then, I follow the link to the current page, which resets the alignment back to the left.

I found a way to sort of fix that problem, by using <a href="#" ... instead of <a href="" .... While this doesn't reload the page (so the text stays aligned), it does take me to the top, which isn't really what I want. I'd like a solution similar to the return false; that works with the inline javascript. Is there a simple way to do this? Or am I doing it wrong completely?


Solution

  • I highly recommend the mozilla developer network for most of these types of answers. It's easy to read and will help you understand JavaScript and the DOM. (JavaScript is good!, DOM is awkward...)

    Specifically, for events: https://developer.mozilla.org/en/DOM/event

    In general, https://developer.mozilla.org/

    There are a few ways to stop events, preventDefault(), stopPropagation(), return false;, or use a JavaScript framework as suggested above. jQuery is good, there are many many others out there (YUI, Dojo, MooTools, etc.), and they all endeavor to make your JavaScript more compatible with different browsers.