Image on off button

Just for the fun I was looking to have a different image on a one off button

I guess I need this part :

background:url(/image.png);
background-size: 100%;

mix with something like this :
#{@{this} == 1 ? "On" : "Off"}

to get something like this :

#{@{this} == 1 ? background:url(/Smiley-8bit_Evil.png) : background:url(/Smiley-8bit_Evil.png)}

or maybe using a If conditional statement ?!

Yep, but pay attention to write a valid javascript code (you should be able to read an error if you open the browser’s console with f12). writing background... as is is an invalid statement in javascript, what you want the script to produce is a string, hence the quotation marks in the on/off example you quoted.

I am just trying to get the image working
#{
backgroundImage = “url(Smiley-8bit_Evil.png)”;
}
But still get an error …

The error as seen in the browser’s console is
ReferenceError: backgroundImage is not defined at line -1

The meaning of this error is explained here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined

To make it valid, you’d need to declare that variable:

var backgroundImage = "..."

But unfortunately that’s not enough to fix it: under the hood, #{} blocks prepend a return statement to the code. So the code would still be invalid because you can’t write return var somevariable = "etc".

Also, declaring a javascript variable called backgroudImage doesn’t automatically assign the css property “background-image”: in the end #{} and JS{{}} blocks are simply replaced with the value returned by the code they contain (provided it is valid of course) and the property’s content will be evaluated afterwards.

This code should work:

#{
  @{this} == 1 ? "background:url(/a.png)" : "background:url(/b.png)"
}
1 Like

Ok I get it !!
I added few parameters (hope it can help some newbie ! )
Maybe is there a way to simplify this, but it took me a few hours to get this

#{
      @{this} == 127 ? "background: no-repeat center/100% url(/A.png)" : "background: no-repeat center/100% url(/B.png)"
    }

How do you get colors in the code when you post ?

If you want to simplify, separate the background property into its different components (background - CSS: Cascading Style Sheets | MDN):

background-repeat: no-repeat;
background-position: center;
background-size: contain;
#{
  @{this} == 127 ? "background-image: url(/A.png)" : "background-image: url(/B.png)"
}

How do you get colors in the code when you post ?

```css
-> css code
```

```javascript
-> javascript code
```

1 Like