Reputation: 621
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.
Upvotes: 1
Views: 186
Reputation: 49218
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.
<img id="sourceImg" src="source.png" title="icon">
<script>
if (screen.width == 1920) {
document.getElementById('sourceImg').style.height = '60px';
}
</script>
That either needs to run after the markup falls in the source of the page, or in a window.onload
event handler. If it runs before the img
element is available, it will error out.
NOTE - JohnFx's method that he describes in the comments below is:
<img id="sourceImg" src="source.png" title="icon" onload="sizeMe()">
<script>
function sizeMe() {
if (screen.width == 1920) {
document.getElementById('sourceImg').style.height = '60px';
}
}
</script>
This uses the img
element's onload
handler. Note that inline event handlers like onload=""
, 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:
<img id="sourceImg"
onload="if(screen.width < 1920) this.style.width='60px';"
src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/001_Jornal_Monsenhor_A_Comarca_23_de_Marco_de_1947.jpg/762px-001_Jornal_Monsenhor_A_Comarca_23_de_Marco_de_1947.jpg"
title="icon">
Note, I changed the if
statement 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.
Upvotes: 4
Reputation: 3951
You cannot do it that way. You are correct - your PHP is interfering. There are lots of ways to do this, just changing your approach:
<script>
document.write("<img src='source.png' title='icon' " + screen.width == 1920 ? "height='60px'" : "" + " />");
</script>
Upvotes: 0