PDA

View Full Version : best practices to change css margin-right with javascript



sniperman
10-04-2009, 02:54 PM
Hi,

I've been working on a solution for a couple of hours now with little result.

The basic action I want javascript to do on an event is to change the css margin-right property of an anchor element.

The HTML

<a name="selector1" id="selector1" href="#" onmouseover="select('1')" onmouseout="deselect('1')"><img src="image.gif" /></a>

The CSS

margin-right:-135px;

The javascript

function select(prop) {
link = document.getElementById('selector'+[prop]); // selects the element for manipulation
link.style.cssText = "margin-right:-160px;";
}

or possibly


function select(prop) {
link = document.getElementById('selector'+[prop]); // selects the element for manipulation
link.style.marginRight="32px";
}

neither of these solutions work. I work with IE7 and it doesn't pick up CSS's margin-right. The attribute shows up in Firebug but nothing happens on the screen.

sniperman
10-04-2009, 03:39 PM
Sorry to bother everyone, i found the solution.

The javascript pointed to the anchor tag rather than the image in CSS. Therefore whatever was applied was applied to the CSS for the a tag. Now it works :)

I should thank myself. Hopefully someone does become my maiden thanker!

jscheuer1
10-05-2009, 03:29 PM
Hmm, it works just fine in both browsers applying the style to the a tag. However, the margin-right property isn't going to do much that is observable with an a tag unless it is contained within something narrower than the body and has some kind of relationship to its container (like being floated right within it for example) that would actually show a visible change of position when the right margin value is changed.

As to best practices, the:


el.style.marginRight = '32px';

form is preferred. Also, in your function you need not assign the element to the variable 'link', but if you do - you should declare that variable formally:


var link = document.getElementById('selector' + prop);

and the nested brackets are not required.

A last 'best practice' that comes to mind here (there could be others I'm missing) is that the events should be attached/added not hard coded to the the elements.

I'd also like to mention, the hover css pseudo class could be used for this sort of thing, no javascript required - that in this case would be a sort of ultimate 'best practice'.