Guiness9889
Guiness9889

Reputation: 71

Is this valid html?

<div class="main" 
     style="cursor:pointer; background-color:#FFFFFF; height:400px; width:500px;" 
     onclick="location.href='http://www.yahoo.com';"></div>

I'm just trying to make it so when click anywhere in the div it acts like a link and takes to a new page. It works, just asking if it is clean/valid. Thanks! ( i left out the first and last < > so it would display here).

Upvotes: 2

Views: 125

Answers (4)

sorpigal
sorpigal

Reputation: 26086

Valid HTML sure, that's pretty easy, good form no.

You should not be using inline style (style="...") unless absolutely necessary; add another class and set your styling there instead. Inline style attributes are one of the cardinal sins if web development, IMO.

You should not be using onclick= to assign javascript events; bind the event with addEventListener instead. This is the correct way of doing things according to the W3C, the onclick method being deprecated, and separates content from logic.

Is there a reason you're not using an anchor (a) tag for this? You can make it a block element by setting display: block; in CSS, it's semantically better to mark up links this way, and it provides graceful degradation if javascript is not available.

Upvotes: 0

Ms2ger
Ms2ger

Reputation: 15983

Valid, yes. Good practice, no. What is wrong with

<style>a.main { background-color:#FFFFFF; height:400px; width:500px; }</style>
<a class="main" href='http://www.yahoo.com'>...</a>

Upvotes: 1

Christopher Tokar
Christopher Tokar

Reputation: 11887

Yes, it is valid HTML however if you really want to do it right you should move the css declarations to a separate .css file and add the onclick event handler dynamically that way you would have complete separation of content and presentation and apply unobtrusive DOM scripting best practices.

The absolute simplest way would be to import jQuery and use the click() method, so you could write something like this:

$('.main').click(function() {
  location.href='http://www.yahoo.com';
});

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

You don’t actually need the <div>, you can just adapt the <a> element’s style so that it is displayed as a block level element by settings display: block for it. This would certainly be a cleaner (and arguably slightly easier) solution.

Upvotes: 5

Related Questions