Chloe
Chloe

Reputation: 21

JavaScript onClick method to change CSS property of an image

I have an image on a HTML page that's set to be blurry in a CSS file. What I want to do is create JavaScript code so when the image is clicked, the image is no longer blurry. Ideally, I would like an onClick event handler to change the CSS file and make the image unblurry.

Alternatively, I have been achieving this by creating a second image which is already filtered as blurry and when onClick occurs, the source of image is changed to the unblurry image. However, this is tedious and would like a simpler way to do it.

Additionally, I would like for the JavaScript to work for numerous HTML pages with images on different pages, instead of including it on each page for that particular image.

Sample code of previous method:

 <html>
 <head>
 <link rel="stylesheet" type="text/css" href="style.css">
 <script src="javascript.js"></script>
 </head>
 <body>

 <div id="image">
    <img id="img" src="imgblur.jpg" height=300 width=300>
 </div>   
 </body>
 </html>

JavaScript:

window.onload = init;
function init() {
var image = document.getElementById("img");
image.onclick = showAnswer;
}

function showAnswer() {
var image = document.getElementById("img");
image.src = "img.jpg";
}

Code for wanted approach:

 <html>
 <head>
 <link rel="stylesheet" type="text/css" href="style.css">
 <script src="javascript.js"></script>
 </head>
 <body>

 <div id="image">
    <img id="img" src="img.jpg" height=300 width=300>
 </div>   
 </body>
 </html>

CSS:

img {
filter: blur(5px);
}

JavaScript:

When image is clicked, the CSS is changed and blur filter is removed.

Thanks in advance :)

Upvotes: 0

Views: 954

Answers (2)

Thiago Souza
Thiago Souza

Reputation: 1191

You can add an onClick method on your image, like this:

...
<img id="img" src="img.jpg" height=300 width=300 onClick="myFunction()">
...

This mean, when your image is clicked, the function myFunction() is called and you do what you need in there.

Upvotes: 0

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Try something like this

Jquery

$('#img').click(function(){
   $(this).css({'filter':'blur(0px)'})
});

Upvotes: 1

Related Questions