switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue:

let bulbImage = $.querySelector(".bulb-image");

let turnOnOption = $.querySelector(".bulb-on");
let trunOffOption = $.querySelector(".bulb-off");

turnOnOption.addEventListener("click" , turnOnFunction);

function turnOnFunction () {
    bulbImage.setAttribute("src" , "./images/bulbon.gif");
}

trunOffOption.addEventListener("click" , turnOffFunction);

function turnOffFunction () {
    bulbImage.setAttribute("src" , "./images/bulboff.gif");
}

Just to clarify, I am not using any framework in this small project and the code is quite simple and straightforward so there should be no bugs.

The HTML code is as follows:

<img src="./images/bulboff.gif" class="bulb-image" alt="bulboff">
<select class="selectbox">
  <option value="Turn ON" class="bulb-on">Turn ON</option>
  <option value="Turn OFF" class="bulb-off">Turn OFF</option>
</select>

Answer №1

function changeImg() {
  if (document.getElementById("select_id").value === 'Turn ON') {
    document.getElementsByClassName("bulb-image")[0].src = "https://images.com/on";
  } else {
    document.getElementsByClassName("bulb-image")[0].src = "https://images.com/off";
  }
}
select {
  border: none;
  margin: 20px 0;
  padding: 10px;
  cursor: pointer;
}

img {
  display: block
}
<select class="selectbox" onchange="changeImg()" id="select_id">
  <option value="Turn ON" class="bulb-on">Turn ON</option>
  <option value="Turn OFF" class="bulb-off">Turn OFF</option>
</select>
<img src="https://images.com/on" class="bulb-image" alt="bulboff">

Answer №2

To change the image when a select option is chosen, you can utilize the change event and select elements values.

<img src="./images/bulboff.gif" class="bulb-image" alt="bulboff">
<select class="selectbox">
  <option value="Turn ON" >Turn ON</option>
  <option value="Turn OFF">Turn OFF</option>
</select>
const
  bulbImage  = document.querySelector('.bulb-image')
, turnOption =  document.querySelector('.selectbox')
  ;
turnOption.addEventListener( 'change', function()
  {
  if ( turnOption.value === 'Turn ON' ) bulbImage.src = './images/bulbon.gif';
  if ( turnOption.value === 'Turn OFF' ) bulbImage.src = './images/bulboff.gif';
  })

You have another option to achieve this using a JavaScript object:

const
  bulbImage  = document.querySelector('#bulb-image')
, turnOption = document.querySelector('#select_id')
, imgSrc =
  { 'Turn ON'  : 'https://picsum.photos/id/1/200'
  , 'Turn OFF' : 'https://picsum.photos/id/2/200'
  }
  ;
turnOption.onchange = e =>
  {
  bulbImage.src = imgSrc[ turnOption.value ];
  } 
select {
  border  : none;
  margin  : 1em 0;
  padding : .4em;
  cursor  : pointer;
  }
img {
  display : block;
  }
<select class="selectbox" id="select_id">
  <option value="Turn ON"  selected > Turn ON  </option>
  <option value="Turn OFF"          > Turn OFF </option>
</select>
<img src="https://picsum.photos/id/1/200" id="bulb-image" alt="bulbOnOff">

Answer №3

<button onclick="document.getElementById('lamp').src='light_on.gif'">Activate the light</button>

<img id="lamp" src="light_off.gif" style="width:100px">

<button onclick="document.getElementById('lamp').src='light_off.gif'">Deactivate the light</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

The onclick button in React is not triggering

I am currently working on a component that processes card clicks and redirects users to a previous route, however, the OnClick function does not seem to be functioning properly. I'm trying to pinpoint where I might be going wrong. function Character ...

Incorporating multidimensional arrays into the `<input type=checkbox>` element

Hey there, I've set up my form in HTML format like this: <input type="checkbox" name="opt[]" value="<?php echo $option['optionname']?>"> Currently, I'm processing the above option[] as an array with just the 'optionn ...

Outputting a variable using javascript

My challenge is to efficiently print the contract variable, which contains HTML content fetched from the server. How can I achieve this easily? I want the print window in Chrome to display the document with the contents of my variable when I click a button ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

Webix UI - Struggling to create dynamically responsive components during screen resizing

Can anyone guide me on how to make my Webix UI control responsive in the free version available at ? It seems to be acting unpredictably due to the AngularJS integration code I'm using. I have attempted various solutions like media queries, redraw, a ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. https://i.sstatic.net/GbphJ.png Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code sn ...

Menu drop down offset in Internet Explorer 7

Having some difficulty with a dropdown menu specifically in IE7. The menu functions correctly in all other browsers, but in IE7 it seems to be misaligned for some reason. Any suggestions or insights would be greatly appreciated. Please refer to the menu co ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

Search for elements with a specific substring in their class names using the querySelectorAll() method

I'm working with a custom component in app.js return ( {cards.map((index) => { return <Card key={index} /> ) Within the Card component, I assigned a specific className return ( <ListItem id="root" className="find-card"&g ...

How to eliminate the unnecessary gap between rows in a Vue div displayed as a grid

I have recently started working with Vue and in my current project, I encountered a challenge where I needed to display 2 players in each row within a div. To achieve this, I utilized the display: grid; CSS property on the playerDiv id. However, I am facin ...

What are some creative ways to format text displayed using ngx-markdown?

I'm currently in the process of building a blog using Angular and I have decided to use Markdown for creating my posts. Specifically, I am looking into integrating ngx-markdown for rendering purposes. As of now, I am developing a component dedicated t ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...

react component failing to update after state change

The layout is not displaying correctly when the state of page changes. Whenever I click on a category link, it verifies if the link exists in the category list. Then, it should update the page state to 'category'. Similarly, clicking on a recipe ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

Unequal height among each div's elements

I'm struggling with creating a footer divided into 3 blocks, but they do not have equal heights, causing the border-right line to appear uneven. Here is a screenshot of the issue: Not equal height of elements Any suggestions on how to fix this? Is m ...

Jquery unresponsive in AJAX form output presentation

I recently delved into the world of jquery and AJAX, and while I grasp most concepts, I'm struggling with a small code snippet. On my webpage, there is a summary of articles. Clicking on an article name triggers a popup window with detailed informati ...

What is the best way to align this div tag with the right side of the box?

.left { width: 50%; display: inline-block; float: left; } /* Second user block */ .right { border-color: lightskyblue; background-color: darkcyan; width: 50%; ...