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

Guide on creating a logarithmic-based bar rating system

I am working on creating a bar rating system for my website, but the current design doesn't look great. I want the height of the bars to increase like an exponential curve gradually, starting off not too steep and gradually increasing afterward. Here ...

Tips for storing a JSON file with GridFS

In my possession is an extensive dataset. Utilizing mongoose schemas, each data element has a structure resembling the following: { field1: “>HWI-ST700660_96:2:1101:1455:2154#5@0/1”: field2: “GAA…..GAATG” } Reference: Re ...

Ensuring Radiobuttons are Selected on a Page After Clicking the Submit Button

Seeking assistance with this issue: I am working on a page that includes radio buttons: <label>Delivery type:</label> <input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick=""><label class="label" ...

Tips for aligning a div within a flexbox to the bottom position

I'm having trouble aligning the div at the bottom of the flex box. I attempted to use align-content: flex-end; but it didn't work. Is there a way to keep the <.div class="parameters"> at the bottom of the row? Especially when the ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

Pass information submitted through a JavaScript prompt to an expressjs endpoint

I'm currently facing a challenge in extracting the value from my prompt in order to modify a category using a JavaScript function. Typically, I would rely on a form to pass variables to the request.body, but that's not an option here. This is wh ...

What is the best way to implement pushstate degradation – using backbone.history or history.js?

I am interested in implementing pushstate functionality, which involves making an ajax request, changing the URL, and adjusting the browser history stack. However, since pushstate is not universally supported by all browsers, I need to find a workaround f ...

Executing asynchronous functions in Angular using ng-click

Within my web application, I am utilizing an ng-table that displays a large number of rows per page (up to 1000). One of the features is a select-all checkbox that triggers an ng-change function to mark each table row as selected. However, the execution ...

The received URL from the POST request in React is now being opened

After completing an API call, I successfully received the correct response in my console. Is there a way to redirect my React app from the local host to the URL provided (in this case, the one labeled GatewayUrl under data)? Any assistance would be greatly ...

Modifying the color of the active column

In an attempt to remove the color from the column border following a click on the image, I am struggling to locate the specific code segment that needs adjustment. I have scrolled through the entire code and experimented with color changes without succes ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

Can an Angular application be developed without the use of the app-root tag in the index.html file?

I'm a newcomer to Angular and I'm trying to wrap my head around how it functions. For example, if I have a component named "login", how can I make Angular render it directly? When I try to replace the app-root tag with app-login in index.html, n ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

What is the reason behind the continual change in the background image on this website?

Can you explain the functionality of this background image? You can find the website here: ...

Tips for initiating a browser file download using JavaScript, ensuring that the download is only carried out if the web service responds with

For a project I am working on, I need to create JavaScript code that will be triggered by clicking on an <a> element. This code will then make a GET request to a web service that I am currently in the process of coding. Once the service returns a fil ...

Utilizing a Node.js web server in conjunction with an Apache Cordova Application

I have created an innovative Apache Cordova Application that leverages a Node.js web server to retrieve data from a web API, enabling the JavaScript-based project to utilize the information obtained from the API. Is there a method to integrate this Node w ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...