-4

I am trying to add the "filter: blur 5px;" affect on CSS to an Id when a Certain Button is clicked. I am wondering how I could change CSS with a JavaScript eventListener or something similar when my Button is Pressed.

G U I
  • 17
  • 4

3 Answers3

1

You can do so by selecting the DOM element to which you wish apply the styles and then inside the event listener to can add the desired styles to the selected DOM element. You can also toggle a class applied to the DOM element. Check the code snippet below:

const btn = document.querySelector("#btn");
const text = document.querySelector("#text");

const btn2 = document.querySelector("#btn2");
const text2 = document.querySelector("#text2");

btn.addEventListener("click", (e) => {
  text.style.filter = `blur(3px)`
});

// Or you can toggle a class on the text element
btn2.addEventListener("click", () => {
  text2.classList.toggle("blur");
});
.blur {
 filter: blur(3px);
}
<div id="text">Hope! This answer is useful</div>
<button id="btn">Blurs the text above</button>

<div id="text2">Thanks for upvoting ;)</div>
<button id="btn2">Toggles blur class on the text above</button>
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

let
button =document.getElementById("btn");
div = document.getElementById("div");
button.onclick = function blur(){

    div.style.filter = `blur(5px)`
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<title>index</title>


</head>
<body>
    <div id="div"><h1>hello world</h1> </div>
    <button id="btn"> add blur</button>

<script src="test.js"></script>
</body>
</html>
Saad Hesham
  • 97
  • 1
  • 9
0

JavaScript provides a style property on HTMLElements.

It's as simple as getting the element (tutorial on that here).

Example:

const btn = document.querySelector("#id-of-button");

Then, (if that element exists), you can access the style property like so:

btn.style = "filter: blur(5px);";

Additionally, if you don't want to reset the style attribute, you can get the certain style you want to change like so:

btn.style.filter = "blur(5px)";

Note that you don't have to add the semicolon at the end (it actually won't work if you do so).

Also, element style properties that are separated with em-dashes in CSS (like flex-direction, are written in Camel Case, like this: btn.style.flexDirection).

You can add event listeners using the addEventListener function:

btn.addEventListener("click", function(event){
  btn.style.filter = "blur(5px)";
});

You can use the event argument passed into the function to get more info about the event, like what triggered it, what type of click it was (right or left click), e.t.c.

Edit:

I forgot to take notice that you want to change another element's style when a button is clicked.

To do this, you can simply change the event listener to this:

btn.addEventListener("click", function(event){
  document.querySelector("#id-of-div").style.filter = "blur(5px)";
});
Reality
  • 637
  • 1
  • 6
  • 25