1

I have been learning Javascript and I'm a little confused as to why this doesn't work. I'd like it so if you click the div, it creates a red border around it:

JSFiddle link

HTML:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> <title>Generation X</title> </head> <body> <script src="test.js"></script> <div id="clickHere" onclick="run()"> <p>Hello</p> </div> </body> </html> 

Javascript:

function run() { document.getElementById("clickHere").style.border = thick solid red; alert("Changed"); } 

2 Answers 2

2

make it ..updated fiddle (you need to wrap it in the head tag)

function run(thisObj) { thisObj.style.border = "1px solid red"; //or "1px solid #ff000" alert("Changed"); } 

also, rather than getting the reference to element again, simply pass the reference during the time of invocation.

Sign up to request clarification or add additional context in comments.

6 Comments

or maybe at the end of body
@AminJafari I was talking about his fiddle configuration.
I've tried this, it doesn't seem to work. Thanks for replying! Guess I don't quite understand your method :p
@DeanHampson did you checked the fiddle i have attached?
Thanks so much, it's the quotes I was missing. +1
|
1

So, instead of putting an onClick on div, use a addEventListener should be better.

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Event_attributes

https://jsfiddle.net/5jsbhbhu/5/

var run = function() { document.getElementById("clickHere").style.borderColor = "red"; document.getElementById("clickHere").style.borderWidth = "1px"; document.getElementById("clickHere").style.borderStyle = "solid"; alert("Changed"); }; var node = document.getElementById('clickHere'); node.addEventListener('click', run); 

2 Comments

Thanks, tony. May I ask; what was the problem exactly? I have no idea how thed event listener made it work.
I don't know the onClick on div is standard or not, I've never put that in div, as presentation should be separation from business logic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.