How Do I make this image responsive with createElement syntax?

I have an image that when clicked on, a larger view appears in the span via JS (the code below).

Question: How do I adjust the script to make the image responsive? That is, width: 100%, max-width: 500px. Right now, the image is stuck at 500px and doesn’t go smaller.

<span id="showImage"></span><br><br>

<a href="#showImage" onclick="showImageSpraying()"><img src="../images/2016-offroad-sun_spraying.jpg" alt="" style="width: 100%; max-width: 200px; border: 1px solid blue;"></a>

    function showImageChampion2() { 
    var list = document.getElementById('showImage'); // empty the span of previous image showing
    if (list.hasChildNodes()) {
    var elem = document.createElement('img'); = 'champion2Id';
	elem.src = '../images/2016-offroad-sun_champion2.jpg';
	elem.maxwidth = '500';
	elem.alt = 'Click to enlarge'; = 'Click to enlarge';        
	var showImage = document.getElementById('showImage'); 

There are a few ways to apply CSS with JavaScript

var list = document.getElementById('showImage');
list.setAttribute('style', "border: 1px solid #F00");

and similar to your invalid line = "1px solid #F00";

* may require camelCase

You can also have JavaScript add a class attribute value, and have the CSS outside of the JavaScript. MHO this is often the most maintainable way.

list.setAttribute('class', "whatever");
.whatever {
  border: 1px solid #F00;

Style properties need to be set through the style property. e.g. = '500';

You’d need to remove this line which won’t be doing anything = 'Click to enlarge';

Continuing the discussion from How Do I make this image responsive with createElement syntax?:

Thanks! That works! Also adding: = ‘100%’; Learning a little more …

Strange - I wanted to reply to a post and ended up making a new one!

I’ll fix it, don’t worry.

You’ve got the hang of it.
@Mittineague’s reply is on the money, there’s a difference between the elements attributes and their DOM properties.

el.className = 'classy';
el.setAttribute('class', 'classy'); = '500px';
el.setAttribute('style', 'max-width: 500px');

Out of curiosity, why would you use JS to apply those styles instead of simply writing them into your CSS file?

I wanted to learn to apply this createElement knowledge. (I used to use innerHTML all the time.)

Also, would the external css work for an image that appears on the page later, as with createElement? Didn’t think of that before.

1 Like

Yes, the external CSS would be applied to every element on the page to which it is addressed (by element, classname, series of elements/classnames, etc) in the HTML.

Thank you. I will test this next!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.