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 automatically invoke a function with the .animate method

I've hit a snag in my jQuery project and could use some help. I'm currently utilizing jQuery's .animate() function like so: $(".planeid").animate({top:'590px'},1000); with an initial top value of 0. Is there a way to initiate a ...

Storing multiple text box values into a single application variable in C# - A Comprehensive Guide

[code page="c#"] Hdnano.Value = Application["AccountNum"].ToString(); $(document).ready(function() { $("#ano").on("blur", function() { var accountNum = $('textarea#ano').val(); $("#Hdnano").val(folioNum); }); &l ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

Finding and choosing a date from an ng-model datepicker using Selenium Webdriver - a guide

I am encountering an issue where I can open the date picker pop-up calendar with a click, but I cannot select a specific date from it. This is due to the input field being read-only, which means that any input provided through sendkeys or JavascriptExecuto ...

Creating form elements without utilizing the <form action: MAILTO:> attribute

I'm in the process of designing a website with a side bar that features a form on every page. I'm looking for a way to have the form information submitted to an email address without using the action: MAILTO:? Would it be possible to create a sep ...

Unable to activate click function in Jquery

Here is a basic HTML page snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> $(document).ready(function () { $('#test').click(); }); < ...

Exploring the Touch Feature in Angular

I am facing an issue with touch events as I am not receiving any useful X/Y coordinates. The event object does not provide the necessary information I need for touch events (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). Despi ...

Press `Enter` to confirm your selection in the BootstrapVue message box input box

Using Vue version v2.6.12 BootstrapVue version v2.21.2 Is there a way to confirm by pressing Enter instead of manually clicking OK? let text this.$bvModal.msgBoxConfirm(<input vModel={text} />) ...

Delete a filename in Internet Explorer with the power of JavaScript and jQuery

In my attempts to clear the file input field in IE using $('#files').val('');, I found that it was not effective. $('#uploadimgdiv').html(''); var fil1 = document.getElementById("files"); $('#fil1').val(&a ...

Is there a way to cancel an AJAX request during the ajaxStart or ajaxSend event in jQuery?

In my project, I have implemented numerous $.post methods and now I need to check the session in each request to handle my page based on session value. However, I don't want to modify all the existing methods ($.post). Instead, I would like to check t ...

Sending HTML input data to jQuery form field

Is there a way to pass HTML text input values into a Stripe form? Here is an example of what I currently have: <input type="text" name="trip" id="trip" value=""> JS: (part of the form) .append(jQuery('<input>', { 'nam ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Is it possible to execute a JavaScript command before the function finishes its execution?

Is there a way to hide a button when a function starts, display some text, and then hide the text and show the button again when the function finishes? I'm struggling with this task because JavaScript doesn't output anything to the screen until ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

Are there alternative methods for anchoring an element in Vuetify aside from using the v-toolbar component?

I have been working on positioning certain elements in the app and I have found a method that seems to work, using code like this: <v-toolbar fixed></v-toolbar> Another option is something along these lines: <v-toolbar app></v-toolb ...

When working in Flask, I am experiencing an issue where my CSS is not linking to my

I am new to coding with HTML, CSS, and Flask and I have encountered an issue where my CSS styling only partially affects my HTML file. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8& ...

Contrasting ./ and $ in React project module imports

The creator of this particular project has utilized a different path to import a component: import { client } from '$lib/graphql-client' I'm curious: What is the significance of the $ symbol in this case? How does it differ from something ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...