Error: Attempting to access the style property of an object that is not defined

My goal is to adjust images by clicking buttons. The JavaScript code should update the image style upon button click, but I encounter an error. Surprisingly, when I try the same operation in my console, it works perfectly.

Below is the HTML code snippet:

<!DOCTYPE html>
<html>
<head>
    <title>Image Modifier</title>
    <style>
        body{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        img{
            width: 50%;
            filter: initial;
        }
    </style>
</head>
<body>
    <img id="pic" src="nature.jpg">
    <button id="contrast" onclick="cont()">Contrast</button>
    <button id="grayscale" onclick="gray()">Grayscale</button>
    <button id="invert" onclick="inv()">Invert</button>

    <script type="text/javascript">
        var image = document.getElementById('pic')
        function cont(image) {
            image.style.filter="contrast(180%)";
        }
        function gray(image) {
            image.style.filter="grayscale(100%)";
        }
        function inv(image) {
            image.style.filter="invert(100%)";
        }
    </script>
</body>
</html>

The following error messages are presented:

Uncaught TypeError: Cannot read property 'style' of undefined
    at cont (first.html:26)
    at HTMLButtonElement.onclick (first.html:19)
cont @ first.html:26
onclick @ first.html:19

Uncaught TypeError: Cannot read property 'style' of undefined
    at gray (first.html:29)
    at HTMLButtonElement.onclick (first.html:20)
gray @ first.html:29
onclick @ first.html:20

Uncaught TypeError: Cannot read property 'style' of undefined
    at inv (first.html:32)
    at HTMLButtonElement.onclick (first.html:21)

Answer №1

One issue you may encounter is trying to pass an image variable to each function, but the variable does not exist, resulting in a return of undefined.

var image = document.getElementById('pic')

function cont() {
  image.style.filter = "contrast(180%)";
}

function gray() {
  image.style.filter = "grayscale(100%)";
}

function inv() {
  image.style.filter = "invert(100%)";
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  width: 50%;
  filter: initial;
}
<img id="pic" src="https://static.passeportsante.net/680x357/i93408-.jpeg">
<button id="contrast" onclick="cont()">Contrast</button>
<button id="grayscale" onclick="gray()">Grayscale</button>
<button id="invert" onclick="inv()">Invert</button>

Answer №2

Consider using const over var for better variable scoping

You can declare your image variable as a constant like this:

const image = document.getElementById('pic')

Alternatively, you can define your variable inside each function using "let"

function cont(image) {
  let pic = document.getElementById('pic')
  pic.style.filter = "contrast(180%)";
}

function gray(image) {
  let pic = document.getElementById('pic')
  pic.style.filter = "grayscale(100%)";
}

function inv(image) {
  let pic = document.getElementById('pic')
  pic.style.filter = "invert(100%)";
}

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

What techniques does Angular2 use to handle dependency injection?

When working with Angular2 components, I know that to inject a dependency, you simply annotate an argument in the constructor, like how ThingService is injected here. However, what I am wondering is how Angular actually knows what to inject at runtime. A ...

Obtain the template as a string within Vue

Let's examine the scenario of having a single file component in Vue with the following structure: // Article.vue <template> <div> <h1>{{title}}</h1> <p>{{body}}</p> </div> </template> If w ...

Modify route title and component if user is authenticated

I've successfully implemented a login feature in my Nativescript-Vue application that utilizes the RadSideDrawer component. My current challenge is to change the route from 'Login' to 'Logout', and I'm struggling to find a wa ...

Finding the timestamp of a blog post in Blogger

Is it possible to retrieve the date and time of a post on Blogger using JavaScript or jQuery? ...

What causes the image to vanish once the CSS animation is activated?

Is there a reason why the image disappears after the animation completes? :/ .coin { width: 200px; height: 200px; background-size: cover; animation: CoinflipRoll 6s steps(199); animation-delay: .5s; animation-fill-mode: forwards; ...

In order to apply a filter express within an array, make sure to utilize variables that

In my Express endpoint, I have various variables that may or may not be present. Depending on the presence of these variables, I need to execute a filter function on an array and apply rules from the req.body. Is there a way to include if conditions withi ...

substituting white spaces in a string with dashes

My task involves taking a string and modifying it so that it can be appended to a query. For instance, I may start with the string "A Basket For Every Occasion" and need it to become "A-Basket-For-Every-Occasion". The process requires locating spaces wit ...

Is there a way to create a link in Javascript that directs to a specific div on a new

Is there a way to create a link that not only opens a new page but also automatically scrolls to a specific section within that page? ...

Is indexed coloring available for vertices in three.js?

I have recently started exploring the world of three.js and I am aware that there is a way to color vertices in three.js. However, I am currently researching whether it is possible to implement indexed colors for vertices in three.js or WebGL. Specifically ...

When working with AngularJS and Karma-Jasmine, it is recommended to flush the $httpbackend only when there are pending requests present

Can I use $httpbackend.flush(); only when there are pending requests? This way, I can avoid receiving: Error: Unflushed requests: 1,2,3,...,n Or Error: No pending request to flush! ...

Using the jquery stop() function will halt any ongoing hover effects from being applied

I am currently experiencing a problem with the code found on http://jsfiddle.net/eSbps/. This specific code pertains to a menu system that reveals second levels when hovering over the top levels, using slideDown('slow'). To prevent queuing effe ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

Ways to extract alt attribute from a converted object and assign it to an element

I'm trying to access the alt attribute of a child div using $this.find in jQuery, but I keep getting an error saying $this.find is not a function. const $ClickedCells = $(".board__cell--black"); function pawnMove() { const $this = $(this)[0] ...

Interpret the JSON reply

Could someone please explain why my function B() is not responding? <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/ja ...

Embed the bootstrap menu within a customized div

I have a unique div containing a combination of CSS styles and a Bootstrap menu. My goal is to integrate the menu within the same div using CSS to achieve the following structure: ABOUT US - HISTORY QUALITY To accomplish this, I intend to insert the tex ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

simulate the act of clicking on a download link by utilizing a secondary click

adown is a link that allows users to download a file from my webpage. It functions properly on the page. However, btndown is a button designed to simulate clicking on the adown link, but unfortunately, it does not work as expected. When the btndown button ...

The JavaScript code is not being executed, as the address bar displays the function name instead

In my project, I have created numerous "js-classes" with various functions spread across different files. Unfortunately, the codebase is too large to share entirely. However, towards the end of the project, I encountered a bug where a specific function wa ...

Modifying a nested array found in select documents

One of my JSON entries stored in MongoDB looks like this: { _id: "fe50fdee-4ea3-4824-94af-f369633c0c7a", _class: "com.tracking.daoservice.model.TrackingData", modified: ISODate("2014-09-10T23:38:48.407Z"), eventtype: "William-Test", eventdata: { Query ...

Summing numbers with multiple queries in Angular services

One of my APIs/projects returns a JSON dataset like this: [ { "id":100, "name":"some name", "x": "y" }, { "id":200, "another name", "x": "z" } ] Another API/costs call returns a similar dataset: [ ...