Wondering how to modify an image source when clicked using javascript and css?

I am looking to create a menu button labeled "menu" that rotates around using rotateX, and then changes into the text "close". Initially, I attempted to achieve this effect with text and animation, followed by text and transform. When those methods failed, I decided to create an .svg of the "close" text already flipped so that I only needed to rotate it 180 degrees.

My main issue is that either the item flips and transforms without transforming as it flips back, or it only works once and fails to function properly afterwards.

const navSlide = () => {
  const menu = document.querySelector("#menu");
  const nav = document.querySelector(".nav-items");

  
  menu.addEventListener("click", () => {
    nav.classList.toggle("open");
    if (menu.src === './icons/menu.svg') {
      menu.src = './icons/close.svg';
      menu.classList.toggle('menu-flip');
    } else {
      menu.classList.toggle("menu-flip");
      menu.src = './icons/menu.svg';
    }
  })
};

navSlide();
#menu {
  font-family: "Syne Regular", Georgia, "Times New Roman", Times, serif;
  font-size: 54px;
  text-decoration: none;
  color: black;
  position: absolute;
  bottom: 0;
  left: 0;
  margin: 0;
  line-height: 42px;
  letter-spacing: -1px;
  padding: 0;
  border: 0;
  background: none;
  transform: rotateX(0deg);
  transition: transform 0.2s ease-in;
  &.menu-flip{
    transform: rotateX(180deg);
    transition: transform 0.2s ease-in;
    letter-spacing: -4px;
  }
}
<div class="menu">
  <img id="menu" src="./icons/menu.svg" alt="menu" />
</div>

Answer №1

(I have provided a solution on a previous post that addresses a similar issue)

For those who are looking to implement a button that dynamically updates the src attribute of an <img> element with a new image each time, please refer to my JSFiddle demonstration here: https://jsfiddle.net/f0a2s6pg/

Alternatively, you can utilize this code snippet:

var imgJson = {"items":[{
    "img": 'https:\/\/picsum.photos\/200\/300'
}, {
    "img": 'https:\/\/picsum.photos\/201\/301'
},
{
    "img": 'https:\/\/picsum.photos\/202\/302'
},
{
    "img": 'https:\/\/picsum.photos\/203\/303'
}
]}

var amount = 0
document.getElementById('imageBtn').onclick = function () {
    console.log("Replacing image...");
    document.getElementById("image").setAttribute("src", imgJson.items[amount].img);
    console.log(amount);
    if (amount == 3) {
        amount = 0;
    } else {
        amount++;
    }
}
<img id="image" src="https://picsum.photos/203/303" style="display: block;">
<button id="imageBtn" style="margin-top: 10px;">Random image</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

Including content without triggering the digest cycle (utilizing raw HTML) within a Directive

My goal is to include raw HTML inside a directive for later transclusion (to populate a modal when opened). The issue arises when the contents of dialog-body are executed, triggering the ng-repeat loop and causing the template to be rerun, leading to a po ...

material-ui DropDown with an image displayed for the selected value

Can someone help me figure out how to display an image in my material-ui dropdown menu? I'm currently using version 0.19.1 and have written the following code: <DropDownMenu autoWidth style={{ width: 500, marginBottom: 30 }} underlin ...

The file upload process did not return a successful response for Ajax

Recently delved into the world of Ajax and encountered a perplexing issue. Here is the dilemma: I successfully upload a .csv file to the server. However, after the upload "success" in the ajax call fails to trigger a response. Neither does complete or er ...

Is it possible to hide Form elements and remove their values simultaneously?

I have implemented a script to display an additional language menu, which functions perfectly. However, I encountered an issue where if the user selects a language and then decides to remove it by clicking on "Remove", the field is hidden but the value sti ...

AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors. angul ...

What is the best way to adjust inline svg to the user viewport size?

After working on integrating my interactive SVG maps into my HTML pages, I encountered a minor issue: when inserting my inline SVG into a standard, non-responsive HTML document, it automatically adjusts itself to fit nicely within the user's viewport. ...

What steps can be taken to ensure this CSS is compatible with all web browsers?

On my Google App Engine application, there is a page that shows search results. While the design and font size look good on my laptop (using Chrome), they appear differently on a larger desktop display with IE. The title seems too large and the text benea ...

Clear HTML

Is there a way to create a 'div' element in an HTML document and adjust the background transparency using CSS or Javascript/JQuery in order to achieve a look similar to Simple Calendar Widget or Glass Widgets from Android? I have tried using the ...

Revamp your D3 interactive graph with real-time data updates from the server!

I am looking to enhance a graph in D3 (or another visualization library) by completing the following steps: When a user clicks on an item, like a node within the graph, New data is fetched from the server, The new data is then used to add new edges and n ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

guide on transferring csv information to mongoDB using Angular and Node.js

I have a CSV file that contains data which I need to transfer into MongoDB using Angular and Node.js. Seeking assistance with reading the data from the CSV file using Angular, parsing it, and storing it in MongoDB. import { Injectable } from '@ang ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

Is it possible to modify the onchange event in a select tag using .attr in JQuery?

CSS <div id=example>This is an example</div> I attempted to modify the content of a div element using the code below: $('#example').text('This is a new example'); //but this did not work ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...

behind the scenes of a disappearing bootstrap modal

Greetings everyone! Currently, I am deep into the process of identifying and resolving a pesky bug that has been impacting my work. The project in question involves developing a module for an open-source platform built on Laravel and Bootstrap - Microweb ...

Guide on setting the dropdown's selected index through JavaScript

Is there a way to use javascript to set the selected value of a dropdown? Here is the HTML code I am working with: <select id="strPlan" name="strPlan" class="formInput"> <option value="0">Select a Plan</option> </select> I am ...

Tips for vertically aligning values in a Bootstrap table

Currently, I am working on generating reports for an NGO that conducts surveys in schools. Once the reports are created, they need to be sent out in a specific format. While a simple table structure would suffice, I have decided to use Bootstrap classes to ...

Gulp does not generate any new folders

Currently, my workspace is located in a directory named "Super gulp" with other directories that contain my files. The issue I'm facing is related to converting my .pug files into HTML files and placing them in the "goal" directory. However, when I tr ...

The PrimeNg confirmDialog is updating my navbar with some modifications

Despite my navbar working well and being fully responsive, I encountered an issue where opening a confirm dialog in the background caused the navbar width to expand to 800px even though the screen width was 1480px, creating empty space on the right side, a ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...