Error: Unable to change image -- TypeError: Cannot assign value to null property 'src'

As I work my way through the textbook for one of my classes, I am practicing by building an image swapping page. The concept is simple - clicking on a thumbnail swaps out the main image and enlarges it as if it were linking to another web page. Despite following the code exactly as it appears in the book, I encounter an error. Here's the code snippet:


var $ = function(id){
return document.getElementById(id);
};

window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");

var imageLinks = listNode.getElementsByTagName("a");

// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
linkNode = imageLinks[i];

// preload image
image = new Image();
image.src = linkNode.getAttribute("href");

// attach event handler
linkNode.onclick = function(evt){
    link = this; // "this" refers to the clicked link

    // set new image and caption based on the href and title attributes
    imageNode.src = link.getAttribute("href");
    captionNode.firstChild.nodeValue = link.getAttribute("title");

    // prevent default action of the event
    if (!evt){
        evt = window.event;
    }
    if (evt.preventDefault){
        evt.preventDefault();
    }else{
        evt.returnFalse = false;
    }
};
}
// focus on the first image link
imageLinks[0].focus();

The error arises at

imageNode.src = link.getAttribute("href");
. Upon inspecting my HTML structure:

<body>
    <h1>Image Swap With JavaScript</h1>
    <p>Click on an image to enlarge.</p>
    <ul id="image_list">
        <li><a href="images/photo1.jpg" title="Golden Gate">
            <img src="thumbnails/thumb1.jpg" alt=""></a></li>
        <li><a href="images/photo2.jpg" title="Rocky Coast">
            <img src="thumbnails/thumb2.jpg" alt=""></a></li>
        <li><a href="images/photo3.jpg" title="Ocean Side">
            <img src="thumbnails/thumb3.jpg" alt=""></a></li>
    </ul>
    <h2 id="caption">Ocean Side</h2>
    <p><img id="main-image" src="images/photo3.jpg" alt=""></p>
</body>

I'm left pondering over why this error occurs. Any insights?

Answer №1

Start with the answer, then go over the lecture... the error in your code is:

<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // taken from html
var imageNode = $("main_image"); // sourced from javascript

The IDs do not match due to a simple typo,

main_image (does not equal) main-image

You can either use

<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main-image"); // in JavaScript

or

<p><img id="main_image" src="images/photo3.jpg" alt=""></p> // found in html
var imageNode = $("main_image"); // defined in JavaScript

To avoid such typos, carefully review your code and variables... happy coding! :)

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

Issues with Stylesheet Rendering in Firefox

Take a look at this Kendo UI Dojo example: https://i.sstatic.net/lVfNM.png When rendered in Firefox, the "right" should also be placed in the header, but it's not. It works correctly in IE11 and Chrome. What am I doing wrong? ...

Node.js TypeError: Unable to access property 'path' of an undefined object

In my Nodejs implementation, I am working on uploading various types of files (photos, mp3, pdf) to Amazon Web Services S3. Right now, I am focusing on uploading an mp3 file but keep encountering the error: "TypeError: Cannot read property 'path' ...

How to temporarily change CSS color for 5 seconds using JavaScript and incorporate an easing effect?

Regarding this query: JavaScript - Modifying CSS color for 5 seconds Here is a live example of the solution: http://jsfiddle.net/maniator/dG2ks/ I am interested in adding an easing effect to the transition, gradually making the color fully opaque and t ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

Issue with automatic compiling in Sublime 2 for less2css

Whenever I try to save my style.less file, the automatic compilation doesn't happen. Is there a mistake in how I've set it up? Here's what is currently in my ox.sublime-project file: { "folders": [ { ...

Attempting to use jQuery on click to set the background image of a div to a base64 encoded data image

Check out what I'm working on here The first div contains html with data:image;base64 <div id="large_photo_null" style="width:50px; height:50px; background-image: url( data:image;base64,R0lGODlhR.. );" > </div> When using html, the ba ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

What is the best way to position a logo and navbar in alignment?

I'm still learning the ropes here. I'm having trouble getting the navbar to align with the logo because margin-top/bottom doesn't seem to be working for some reason. <HTML> <HEAD> <link href="style.css" rel="stylesheet"&g ...

Sending data to a Bootstrap modal dialog box in an Angular application

Using span and ng-repeat, I have created tags that trigger a modal pop-up when the remove button is clicked. Within this modal, there is a delete button that calls a function. I am trying to figure out how to pass the id of the remove button to the modal ...

Transition smoothly with a fade effect when switching between models

I am in the process of creating a basic query system. While I can display questions one at a time, I am looking to incorporate transitions when switching between questions. To further illustrate my issue, I have set up a Plunker demonstration: http://plnk ...

Performing a reverse image search request using Javascript/AJAX to query Google

I have been attempting to perform a reverse image search request using AJAX, but I keep receiving 302 errors. After checking the Firebug console, I discovered that the response header from Google contains a URL linking me to the results. However, I am unsu ...

JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters. Check out my code snippet below: function oppC(){ var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "co ...

Implementing a Bootstrap datetime picker using the hh:mm:ss time format

I'm currently developing an application and I've run into a roadblock with the datetimepicker feature. I need the datepicker to display the date format as yyyy-mm-dd hh:mm:ss (year, month, and date with the current hour, minutes, and seconds). It ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Is there a way to transform JSON text into a JSON object?

Similar Question: How do I convert JSON to a JavaScript object? { "data": [ { "name": "JoongBum Lee", "id": "526210623" }, { "name": "\uc774\uc778\uaddc", ...

What could be causing the favicon in my Next.js application to not function properly?

My favicon doesn't seem to be working properly. I've saved the favicon file as favicon.ico in the /public directory and have included a reference to it in the <Head> section of my pages (which are located in the /pages directory), but it s ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

Unexpected behavior from Internet Explorer - Span contents remain unchanged despite valid input

I have a simple question because I'm feeling a bit lost. Check out this JSFiddle link It seems that in Internet Explorer, the contents of my span won't update even though the input is valid. However, in other browsers, the span content changes ...

What is the best way to make Bootstrap 3 move to a new line when there is not enough space?

I am facing an issue with a lengthy text inside a div with a class of "col-md-3". The text is so long that it appears to be overlapping with the content of another div. Adding spaces is not an option as it is an email address, and it displays fine on some ...