Uncaught TypeError Cannot read property 'style' of undefined

Viewed 2808

I am trying to modify images using button click. The js is supposed to update the image style on button click but it gives error. But when I try the same on my console it works.

This is my HTML Code

<!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>

It gives me the below error

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)
2 Answers

The problem is that you're passing an image variable to each function, which doesn't exist, thus returning 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>

Try to use const instead of var

const image = document.getElementById('pic')

or define your variable inside each function with "let"

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

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

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