When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code.

<html>
<body>
 <script type="text/javascript">
   function changeImage() {
     var image = document.getElementById('myImage');
     if (image.src.match("bulbon")) {
          image.src = "C:\Users\ashokch\Desktop\light_bulb_off3.jpg";
     } else {
       image.src = "C:\Users\ashokch\Desktop\bulbon.png";
    } 
 }
</script>

  <img id="myImage" onclick="changeImage()"
    src="C:\Users\ashokch\Desktop\light_bulb_off3.jpg"      width="100" height="180">


      <p>Click the light bulb to turn on/off the light</p>

      </body>
   </html>

When the page loads in the browser, the default image displays. However, when I click the image, the new image does not load as expected.

Answer №1

When trying to access files, avoid using invalid file protocols like (file:///C:/mydir/index.html). It is recommended to place the files in the same directory as your HTML file and reference them simply by the file name (e.g. light_bulb_off3.jpg), or update the paths to a valid format (e.g. file:///C:/Users/ashokch/Desktop/light_bulb_off3.jpg)

Answer №2

Here is a helpful tip:

<img src="file:///C:/Users/ashokch/Desktop/light_bulb_off3.jpg">

Make sure to remember the use of the file:/// protocol handler. Also, remember to use / (forward slash) instead of \ (backslash).

This method is specifically used to display local files in your web browser.

However, this only applies to local files.

If you want to serve these images through a web server, you need to create a folder within your web server's root directory.

For instance,

/images

You can then save your images in this created folder.

After that, adjust the image src or javascript attributes to the absolute path.

<img src="/images/my-image.jpg">

This will take the current URL, remove the hostname and protocol, and add the src.

For illustration purposes:

http://www.example.org/folder/test.html

<img src="{http://www.example.org}/images/my-image.jpg">

<img src="{http://www.example.org/folder/}images/my-image.jpg">

<img src="http://www.some-image-host.com/xyz123.jpg">

Absolute refers to having the protocol and hostname/path.

Relative refers to being relative to the root of your current domain (without any path).

Answer №3

Feel free to upload your pictures to a reliable image hosting platform such as:

or

After uploading, use the new links to view your images and make sure they are working properly.

"bulbon" ??? Have you heard of it before?

Answer №4

To ensure proper image path linking within your project, make sure to reference images relative to the project directory rather than the file system itself. You can achieve this by copying the images into the project folder or providing a corresponding relative path. This approach will effectively resolve any related issues.

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 jQuery to replace this color with that color in CSS every time it appears

I have numerous div elements, some with a background-color: #aaa, others with font color: #aaa, and some with border-color: #aaa. There are also divs with various other colors. I am looking to update these colors (#aaa) to #ccc throughout the CSS. While ...

The selected custom button color is not appearing as intended when viewed in the

I'm currently in the process of creating a small webpage dedicated to showcasing my top favorite Zelda bosses using HTML, CSS, and Bootstrap 5. To make it more personalized, I decided to veer away from the standard Bootstrap button colors and create m ...

Iterate over a JSON array using jQuery

I am attempting to iterate through this data to extract the 'name' values. Here is my current code, but it does not seem to be functioning correctly. I have tried a few variations from suggestions here, but none of them have worked. $.get("/ ...

Interpolating UV is not allowed: 'flat': Using a reserved word in an illegal manner

As a beginner, I recently learned that UV coordinates are not interpolated in WebGL, allowing for exact pixel values to be retrieved. However, when attempting to use the 'flat' keyword, I encountered an error. By adding 'flat' before t ...

Issue with locating image source in Angular 4

I'm struggling to source an image using angular 4. It keeps giving me an error message saying that the image cannot be found. Here is my folder structure: app_folder/ app_component/ - my_componenet - image_folder/ - myimage I am trying to ...

Saving a user with a BLOB avatar in Angular 5: Tips and Tricks for Success

As a newcomer to Angular, I am trying to figure out how to properly save a new user with an avatar. Can someone help me understand how to pass the Blob value of the avatar to my user Model for successful saving? Below is the code snippet I am working with ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

How to use ajax to add multiple products to the cart in WooCommerce using a single add-to-cart button?

My goal is to utilize ajax in order to add multiple, distinct products to the cart with a single click of a button. The AddToCart-Button is located in SHOP before pagination. Whenever I try to add multiple products to the cart at once, the Ajax request is ...

Incorporate a unique element onto your WordPress homepage

I'm seeking guidance on how to incorporate a custom feature (including a textbox and a button) onto my WordPress homepage. My goal is to create an area where users can input a code into a textbox. Here's the challenging part: Once the user click ...

Struggling to make addClass and removeClass function correctly for the development of the unique "15 puzzle" game

I am currently in the process of creating a version of "the 15 game" using jQuery in HTML. You can find more information about the game on this page. The objective of the game is to rearrange a table of "boxes" in ascending order from 1 to 15. Below is th ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

Has the HTML attribute 'step' stopped functioning properly?

I'm currently working on an Angularjs project that primarily uses material design. I am trying to set up a timepicker using the input control with the type=time attribute. However, I want to restrict the user to select times only within a 30-minute ra ...

Creating dynamic child components in Vue.js version 2

I am currently developing a facet search system using VueJS. The concept is fairly straightforward: Within a FilterGroup component lies the overarching filter logic. This component allows for several child components, such as AttributeXYZFilter, to provid ...

Why does my navbar toggler automatically display the navbar items?

I am perplexed as to why the navigation items keep appearing every time I refresh the page in mobile view. Despite checking that aria-expanded is set to false, it still does not seem to work. Below is the code snippet: <html lang="en"> & ...

The parent div's height is not compatible with the CSS grid

I created a CSS grid layout featuring a header, side menu, and scrollable content. My goal is to test this layout in a container div where I've specified the width and height. The layout adjusts well according to the container's width, but seem ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

Avoiding duplicate borders in grid layout

I'm working on a crossword puzzle design using css grid The blank cells have no color, while the other cells have a black border. The issue I'm facing is that the borders are overlapping. I've referred to similar questions on Stack Overfl ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...