Javascript add class if localStorage value exists without reloading page

Issue

I work on ionic 5 and angular and I need to change the DOM of my view after a modal popup. The problem is that I have to reload the view to see the DOM modifications, and I need it to change without any reload.

First step add key and value in LocalStorage and modal appears on element click.

Second step I need a addCLass(‘hide’) on divs when modal is dismiss.

Any tips to make these changes without reloading the page ?

HTML code :

    <div class"circleImgContainer">
  <img class"suivezLaRecoImg" src"../assets/imgs/muscu_cardio/circleRecommandation@2x.png" alt"">
  <img class"demarrerVosRepImg hide" (click)"goReps()" src"../assets/imgs/muscu_cardio/demarrerVosReps@2x.png" alt"">
</div>

Ts :

  ngOnInit() {
let content  document.querySelector(".circleImgContainer");

if (localStorage.getItem('serie_1')  'true') {
  content.classList.add('hide');
}

}

Solution

I believe in this case you can use setInterval to always check if a localStorage has the desired value and change page content without having to reload.

Here’s an example below, normally you can provide setInterval with a time (in milliseconds) interval, but without, it will always constantly update if the if statement matches your set condition.

setInterval(() > {

  ngOnInit() {
    let content  document.querySelector(".circleImgContainer");

    if (localStorage.getItem('serie_1')  'true') {
      content.classList.add('hide');
    }
  }

})

Answered By – Cohen

Leave a Comment