Link to home
Start Free TrialLog in
Avatar of xenium
xenium

asked on

How to turn an image opaque on click (with text overlay)

hi,

I want to create a simple series of thumbnail images that when clicked turn opaque, or clear (toggle on/off opacity when clicked)

Ideally I'd like to overlay text on the images, so I expect SVG is good for that, but may make the above harder.

Can anyone give some example code or point me to an example I can drill into?

This is for a simple visual shopping list.

Thanks
Avatar of xenium
xenium

ASKER

Here's a snippet that toggles opacity on or off after a long press (2 seconds)

https://www.w3schools.com/code/tryit.asp?filename=FY0EZJ8QFMC2

I'd like to apply the same logic to any number of images. What's a neat way to do that?
Avatar of xenium

ASKER

hi Juana, thank you. That's useful in learning as I'm new to the game here, however i think the effect i need is different

* * *

The following does what I need for object "Item" I want to do the same for Item2 but without hardcoding for each item.

https://www.w3schools.com/code/tryit.asp?filename=FY0EZJ8QFMC2
Avatar of xenium

ASKER

Here is a simple implementation: https://www.w3schools.com/code/tryit.asp?filename=FYBG33SKPGC2

However it only seems to work after the second click: why is the opacity not being picked up initially?

<div class="items" id="item1">
  <img src="https://www.ocado.com/productImages/247/24720011_0_640x640.jpg" alt="bisto" style="width:30%; opacity:1">
</div>
<div class="items" id="item2">
  <img src="https://www.ocado.com/productImages/198/19840011_0_640x640.jpg" alt="bisto" style="width:30%; opacity:1">
  
  <script>

var classname = document.getElementsByClassName("items");
for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}
  function myFunction() {
   
   var opacity = Number(this.style.opacity);
   //alert(opacity);
   
   if (opacity > 0.5) {
    	this.style.opacity = "0.3"; 
  		} else {
   		 this.style.opacity = "1"; 
  		}
    
}
  </script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xenium

ASKER

Thanks again, yes that makes sense. By mistake I had put the default opacity within the img instead of div. That's fixed now...

https://www.w3schools.com/code/tryit.asp?filename=FYCLG49KDB17
Glad to hear that, good job, you're welcome anytime.