0

Assuming that we have html like the one below, I want to be able to click on the element using javascript just as if I it was a link.

<li class="myClass" data-type="onClick" data-target="something://url">
    <img src="img.png" alt="image"/>
    <h2> Text</h2>
</li>

Thanks

5
  • just add onclick="some_function();" to your li tag? Commented Sep 21, 2011 at 14:02
  • 1
    Just a note (may save from styling issues in the future), there's an extra space in front of your text in the h2 element. If you want padding, add .myClass h2{padding-left:3px;} to your css. Commented Sep 21, 2011 at 14:11
  • @Beez That space character has no effect on the presentation of the H2 element. Commented Sep 21, 2011 at 14:22
  • Really? I didn't realize h2 elements ignored white-space...I'll have to read the spec, now. Thanks, @Vidas Commented Sep 21, 2011 at 14:38
  • H'm. Doesn't say anything about it. Well, it appears you're right, still. I thought it only ignored spaces > 1. Good to know! Thanks! Commented Sep 21, 2011 at 14:58

2 Answers 2

2
<li class="myClass" onclick="doSomething()">
    <img src="img.png" alt="image"/>
    <h2> Text</h2>
</li>

In your javascript create the function doSomething()

And maybe use CSS on the li element:

li.myClass {
    cursor:pointer;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could also use jQuery. It's more easy to work with jQuery. There you would give the li element an id or a class and then you could use this code:

$(".myClass").click( function() {
 // .. do the code
});

or with id:

$("#myID").click( function() {
 // .. do the code
});

I would also advise to put a pointer on the element by adding " cursor: pointer; " to the css. So everyone knows it's possible to click on it :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.