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

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

Utilize jQuery post to send a request to a particular function located at a given URL

Is there a way to accomplish the following: $.post( "functions.php", { name: "John", time: "2pm" }) .done(function( data ) { alert( "Data Loaded: " + data ); }); Instead, is it possible to direct your data to a particular function in "functions.p ...

utilizing the removeClass method to toggle the visibility of a div by removing the "hidden" class

I am currently developing a dynamic game utilizing HTML, CSS, and jQuery. In the lower right corner of the screen, there is a question mark (which is an image file, not text). My objective is to display a help box when the question mark is clicked and held ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

Commit the incorrect file name with the first letter capitalized

There seems to be an issue with the git not recognizing the correct filename casing. I have a file named User.js in my workspace, but when checking the git status, it displays user.js instead. Despite repeatedly changing and committing as User.js, the gi ...

What is the method to access 'let' variables in the console of a developer tool?

When you open the Chrome devtool and enter the code snippet below: // The iife is irrelevant let r = (() => { return 2; })(); and then evaluate r, the output will be: r 2 Surprisingly, both window.r and globalThis.r return undefined. Although let is ...

How to style text in CSS with a numbered underline beneath

Is there a way to apply underlining to text and include a small number underneath the underline in a similar style shown in this image, by utilizing css, html, or javascript? ...

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Using jQuery to update the CSS class for all li icons except for the one that is currently selected

Utilizing Font Awesome Icons within the li elements of a ul Challenge When a user clicks on the user icon, the color changes from black to yellow. If the user clicks on another icon, that one also turns yellow. Is there a way to remove the existing yell ...

Encountering an issue while updating information following the migration to vue-chartjs 4

I recently upgraded from vue-chartjs version 3 to version 4. I successfully migrated my LineChart component by updating the template section and removing the draw method calls. This component is utilized for two separate charts. However, when I close the ...

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Triggering focus on an MUI Input component upon clicking outside its designated region

Currently, I am working on an application using ReactJS and Material UI. Within this project, I have incorporated an Input component inside a FormControl component. My goal is to have the focus automatically set on the Input component whenever a user click ...

implementing dynamic binding of image src paths to backend data in a vue js application

Is there a way to bind the image src path to backend data in Vue.js? I'm familiar with how to do it on the frontend using: <img :src="require(`@/assets/${item.image}`) But how can I achieve this with backend data? ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

Looks like an error has occurred: "Swal has not been defined"

I'm currently working on a small project that involves using CodeIgniter, VueJs, and the Sweet Alert Javascript library. However, I encountered an error in my console stating ReferenceError: "Swal is not defined" when I try to call swall.fire({}) with ...

Changing the structure of divs by using elements from different divs

I'm looking for some help with adjusting the CSS of a div when hovering over certain elements. Here is my current code: <div class = "container-main"> <div class = "container-inner"> <ul class = "list"> &l ...