I am looking for the proper method to embed javascript into an html parameter. This is an example of what I am trying to do:
<img src="source.png" height="<script> if(screen.width == 1920)
{document.write('60px');}</script>"
title="icon"/>
I know embedding PHP in this manner can work, but I can not seem to get it to work with Javascript. My limited knowledge on the matter is to blame, and I need some help resolving this issue. Thanks.
Note the
id="sourceImg"I added to the element, which must be unique per element per page. Not doing this will mean Javascript will not know which element to select, and will pick one.That either needs to run after the markup falls in the source of the page, or in a
window.onloadevent handler. If it runs before theimgelement is available, it will error out.NOTE – JohnFx’s method that he describes in the comments below is:
This uses the
imgelement’sonloadhandler. Note that inline event handlers likeonload="",onclick="", etc., are typically considered hard to maintain. The above should work, however, as a demonstration, and other routes involve understanding page loading, DOM element availability and other details which are potentially more difficult to understand than a simple example.EDIT
And, technically, you could do this:
http://jsfiddle.net/pdN3y/
Note, I changed the
ifstatement to make the change more obvious.But please don’t. It’s a bad idea and a bad habit to get into. Spend some time figuring out page loading and DOM availability, it’s time well spent.