Is it possible to gradually decrease the blur of an image in JavaScript using a loop and a variable?

I'm experimenting with something like this:

let str = 10;
let blu = "px";
let val = "";

function check() {
    if(a < b){
    str = str - 6;
    if (str<0){str = 0}
    val = str+blu;
    document.getElementById("img1").`style.filter = 'blur(val)';
}

The value of 'str' and therefore 'val' changes every time the function 'check' is executed, but 'blur(val)' results in an error.

I was under the impression that a variable could be used here. I also attempted using setProperty.

document.getElementById("img1").style.setProperty("blur", val);
but this also led to an error.

What would be the solution? Also, how can you gradually reduce the blur effect on text or an image based on a timer? For instance, if the initial blur is set to 60px, reduce the blur by 1px every second so that after 1 minute, the entire text becomes clear?

Answer №1

Why not consider implementing a CSS transition for a smoother effect instead of using JavaScript? It's simple and elegant.

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('.image1').classList.toggle('blur')
})
.image1 {
  display: block;
  margin: 3em auto 0;
  transition: 2s;
}

.image1.blur {
  filter: blur(20px);
}
Wait for the image to load, then click on <button>toggle blur</button>
<img class="image1" src="http://picsum.photos/300/100">

Answer №2

  1. Utilize template literals (backticks) in the appropriate place, as there seems to be a stray one in your code
  2. Allow the browser sufficient time to repaint the content
  3. Optimize performance by caching the element

document.addEventListener('DOMContentLoaded', () => { // ensure page elements are loaded
  let str = 60;
  let tId;
  const img = document.getElementById("img1")

  const check = () => {
    str -= 10;
    if (str < 0) {
      clearInterval(tId); // stop interval
      return;
    }
    let blur = `blur(${str}px)`;
    img.style.filter = blur;
    console.log(blur);
  }
  tId = setInterval(check, 1000); //establish loop
  check(); // execute immediately
})
#img1 {
  filter: blur(100px)
}
<img id="img1" src="https://picsum.photos/200/300" />

<img id="img1" src="https://picsum.photos/200/300" />

In this portion, I made educated guesses about what you intended with variables a and b

document.addEventListener('DOMContentLoaded', () => { // when page elements are ready
  let str = 60;
  let a=10;
  let b=0;
  let tId;
  const img = document.getElementById("img1")

  const check = () => {
    if (a < b) { // unclear on this part, consider removing if not needed
      str -= 10;
      if (str < 0) {
        clearInterval(tId); // halt execution
        return;
      }
      let blur = `blur(${str}px)`;
      img.style.filter = blur;
      console.log(blur);
    }
    a--;
    b++;
  }
  tId = setInterval(check,1000); //run loop
})
#img1 { filter: blur(100px) }
<img id="img1" src="https://picsum.photos/200/300" />

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

Steps to conceal an accordion upon loading the page and reveal it only when clicking on a specific element

Below is the code I am using to display an accordion in a Fancybox popup. However, I do not want the accordion to be visible on page load. If I hide it, the content inside also gets hidden when showing the accordion in the popup. When user clicks on Click ...

"Incorporate a personalized dropdown menu (using the datatables plugin) in the designated design structure

Is it possible to add a dropdown list next to the search field in the datatables plugin without positioning it outside where the plugin is initialized? I want to have a custom dropdown list with fixed values, similar to this: https://i.sstatic.net/Fm4zs.pn ...

Guide on making a dynamic table with HTML and CSS featuring square cells

Looking to design an 8x8 table using HTML and CSS, with the first column and row functioning as headers (ideally with header row height equal to header column width), and all table body cells being square. Shown below is the current HTML and CSS code: < ...

Slide back with jQuery when a user clicks anywhere on the webpage

$(".links").click(function(){ $('.slider').stop(true,false).animate({ right: "0" }, 800, 'easeOutQuint'); }, function() { $(".slider").stop(true,false).animate({ right: "-200" }, 800, 'easeInQuint'); }, 1000); I ...

How can I include additional lines in a 3D model?

https://i.sstatic.net/NH1sB.png In my latest project using three.js, I created a 3D human model and now I want to enhance it by adding angle lines similar to the red ones I manually drew on the image. Does anyone know how to achieve this effect? ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

The Ajax success or error message is only shown one time

I have successfully created a form using php, ajax, and JavaScript. By implementing ajax, I am able to display error/success messages without redirecting the user to another page. Everything works as expected when I use console.log to showcase these mess ...

Utilizing Immutable.js to handle state changes in React applications

I'm struggling to properly change the state using setState in React.js while working with Immutable.js. The documentation doesn't provide clear instructions on how to achieve this. Here is the function I'm currently using: createComment(co ...

Using conditional routing for nested routes in VueJS

Is there a way to conditionally redirect a children route? I've experimented with various methods but haven't had any success. Currently, I am using a state from the store as the condition to redirect the children routes. I have exported my stor ...

Swap out HTML lists for a PHP array structure

For my assignment, I was tasked with creating an HTML list from an array and generating a drop-down menu based on another array. The requirement is that when a particular subject is selected from the drop-down menu, only that subject along with its teacher ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Creating dynamic layouts using Handlebars.js recursion

I'm working with a basic object hierarchy that includes: Category String name List childCategories; My goal is to use handlebars to represent this structure in a generic manner, but I'm struggling on how to nest layouts. Here's the curre ...

In what way can I fill out my search fields using the criteria included in the URL?

In the process of developing an asp.net web application, I have implemented a code snippet to construct a section for search fields. This code builds URL parameters based on user input: <script type="text/javascript> $(document).ready(function(){ ...

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

Is it possible to utilize THREE js ExtrudeGeometry to manipulate a shape along a jagged path?

Is it possible to use CatmullRomCurve3 to extrude over a sharp line, as shown in the image below: https://i.sstatic.net/wJNEv.png I am looking to achieve the following result: https://i.sstatic.net/Fe87K.png The goal is to achieve this with minimal pol ...

Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser. <!DOCTYPE html> <html> < ...

Creating a customized SelectField component for Material-UI v1.0.0-alpha.21 with a fix for the Menu anchorEl problem

Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components. Below is the code for my custom selectField: export default class SelectField extends Rea ...

Issue with dropdown menu appearing beneath specific elements in Internet Explorer versions 7 and 8

I've been encountering some troublesome issues with a website I'm working on, specifically in Internet Explorer 7/8. On certain pages, the navigation elements are getting hidden below text and images, causing confusion for me. I've attempted ...

What is the process for transforming a JSON string into an array?

code page="c#" { "data": [{"CUSTOMER_NAME_ID":"INV10143","CUSTOMER_NAME":"rossperry","CUSTOMER_NAME_PAN":"AVRPG4803D","EMAIL":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97e5f8e4e4e7f2e5e5eea6d7f0faf6fefbb9f4f8fa"> ...