Click event not triggering to update image

I'm currently working on a Codepen project where I want to use JavaScript to change the image of an element with the id "chrome". However, my code doesn't seem to be working as expected. Can someone help me troubleshoot and fix this issue? Your assistance is greatly appreciated.

The main goal is to modify the image of an element with the id of "chrome" when it's clicked.

Link to the Codepen

Below is the JavaScript code snippet that I have been using:

function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png") 
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else 
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}

Essentially, I want to replace the chrome icon with an X image when it's clicked. Any insights on how to achieve this would be really helpful.

Answer №1

Modify the tag from

<img onclick()="changeImage()">
to
<img onclick="updateImg()">

Answer №2

To start, modify the

<img onclick()="changeImage()"
to <img onclick="changeImage()". This adjustment will not resolve your issue if you aim to implement it for multiple users, as every chrome image necessitates its individual ID for the function to operate on various logos.

Answer №3

You made an error in your code. In the inline onclick definition, you wrote:

<div onclick()="changeImage()"></div>

The correct syntax should be:

<div onclick="changeImage()"></div>

Check out the snippet below:

function changeImage() {

        if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png") 
        {
            document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
        }
        else 
        {
            document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"
        }
    }
img {
height: 25px;
      padding-right: 4px;
}
li {
margin: 4px;
      clear: both;
}
li:nth-child(odd) { 
background: #f0f0f5; 
}
<ul class="list-unstyled">
<li>Username<span class="pull-right">
          <img onclick="changeImage()" id ="chrome" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right"><img id="firefox" src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
          <img id="ie" src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>

</ul>

Answer №4

Replace the function call from onclick()="changeImage()" to onclick="changeImage()". Make sure to remove the "()" brackets in the onclick function.

Answer №5

Your HTML code contains a syntax error. Remember that onclick is an HTML attribute, not a function, so it should not be called with parentheses like a function.

You only add parentheses to the value of the onclick attribute when using JavaScript syntax.

To correct this, your code should look like this:

<img onclick="changeImage()">

To see a working version of your code pen, visit: https://codepen.io/pahund/pen/XgWVQx

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

Animating Brightness and Contrast in CSS

I come from a strong background and I am looking to create a dynamic loop that changes the brightness using CSS specifically on Chrome. The goal is to have the background color match the user's profile, providing a unique experience each time. For ex ...

Utilizing JQuery to capture user input in a textarea and showcase it in a span element with key press

Is there a way to capture the user's input and display it in a span above the textarea? Specifically, how can I detect when the user presses the enter/return key (keyCode 13) and correctly insert a line break ( ) in the span? $('#InviteMessage ...

What is the best way to conceal the URL of a link leading to a file?

My website is built with C#, Kendo MVC, Razor and features a Kendo grid where one of the cells contains a hyperlink to a PDF file. The issue I'm facing is that when users click on the link, the URL is visible in the browser and can be altered to acces ...

Issues with TypeScript "Compile on save" functionality in Visual Studio 2015

The feature of "Compile on save" is not functioning properly for me since I upgraded to Visual Studio 2015. Even though the status bar at the bottom of the IDE shows Output(s) generated successfully after I make changes to a .ts file and save it, the resul ...

Toggle the flag status of a checkbox based on the response provided in dialogues (Angular)

Query: I am facing an issue with my checkbox system where a dialog pops up when trying to unflag a form by unchecking the box. The dialog asks for confirmation before removing the form. How can I ensure that the checkbox remains checked until the user clic ...

Getting Bootstrap columns to work well with Angular ng-show

I am working with three columns in Bootstrap, all set to col-md-4 width. The middle column has an ng-show attribute that may hide it at times. When the rightmost column becomes visible due to friend requests, it displaces the middle column if it's hid ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Use vanilla JavaScript to send an AJAX request to a Django view

I'm attempting to make a GET AJAX request to a Django view using vanilla JS. Despite passing is_ajax(), I am having trouble properly retrieving the request object. Below is my JavaScript code. Whether with or without JSON.stringify(data), it does not ...

How can I extract data from a swiffy animation?

Suppose I am tracking the number of mouse clicks in Flash. To do this, I have utilized the following code: import flash.events.MouseEvent; plus.addEventListener(MouseEvent.CLICK,aaa) var i:int=0; function aaa(e:MouseEvent) { i++; var a:Number ...

I am seeking assistance with incorporating mySQL into my Node.js project with React

Currently, I am working on a web-app utilizing Node.js. The main goal is to retrieve information from my local database in MySQL Workbench. Initially, I decided to focus on building the frontend interface before diving into implementing the functionality s ...

What could be causing my transform scale to not function properly in Bootstrap?

As a complete beginner, I am currently in the process of learning bootstrap. I have noticed that the animation breaks when I apply it, specifically the scaling part. Interestingly, the animation works perfectly fine without Bootstrap. I am wondering if the ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

Algorithm for converting a 2D voxel map into a line may encounter occasional difficulty in progressing

For my game, I am dealing with a 2D voxel map stored as a 2D array where 1 represents ground and 0 represents sky. In the map, areas marked as 1 (ground) are represented by green boxes The algorithm initiates at the leftmost ground voxel touching the sky ...

How can we create responsive websites?

Since starting my Software Developer studies about 3 months ago, I've been working on a website project for a driving school with a team of four. The issue we're facing is that when we transfer and open files between laptops, the website layout a ...

Combining Files with Gulp.js and Handling File Names

I need a solution that will add the file name as a comment to each file in the stream. This means creating a comment line with the file path in the final destination file. The current functionality is as follows: pseudocode: concat(file1, file2) # outpu ...

How can you define & specify parameters for iframe using CSS?

Is there a way to style the parameters of an <iframe> using CSS? I am trying to embed multi-track audio from archive.org. For example, like this: <iframe src="https://archive.org/embed/art_of_war_librivox​&playlist=1​&list_height=200 ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Guide to creating a delayed response that does not block in Node and Express

I want to implement a delayed response to the browser after 500ms has elapsed. app.post('/api/login', function(req, res) { setTimeout(function() { res.json({message: "Delayed for half a second"}); }, 500); }); The code snippet a ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Ways to stop a JS plugin affecting HTML anchors and preventing them from automatically scrolling to the top

My friend is working on a website and he's using a plugin called Flip Lightbox. The basic functionality of the plugin is that when you click on an image, it flips over and pops out as a lightbox. Everything works fine, however, if you scroll down the ...