0

I would like to run a function that would run when the box width reaches certain pixel, lets say 80px. lets say I want to alert "hello" and console.log "hey". How would i be able to accomplish this? And I can't use jQuery, so just vanilla Javascript please.

Edit: I wonder if I could insert something like a function that runs the alert or console log when redbox.style.width == "80px"?

const redbox = document.querySelector("#redbox");
const coolbutton = document.querySelector("#coolbutton");

coolbutton.addEventListener("click", animator);
function animator() {
  if (redbox.style.width == "50px") {
   redbox.style.width = "100px";
   redbox.style.transition = "2s";
  } 
  else {
   redbox.style.width = "50px";
   redbox.style.transition = "2s";
  }
} 
#redbox {
  background: red;
  height: 50px;
  width: 50px;
}
<div id="redbox"></div>
<button id="coolbutton">click</button>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
craftdeer
  • 985
  • 5
  • 20
  • 36

2 Answers2

1

To sum up, there is no event handler (natively) for during an animation transition. There is however one for transition end that would work natively with your code, but since you want to grab its width during the middle, without jquery, that complicates things.

I have little experience with request animation frame but for now, after tinkering a bit with your code, here is a structure using a good old fashioned setinterval timer that should get you started with what you want to do.

const redbox = document.querySelector("#redbox");
redbox.style.width = `50px`;
const coolbutton = document.querySelector("#coolbutton");
coolbutton.addEventListener("click", animator);
let toggle = true;
function animator() {
  let poller = setInterval(function(){
    let w = parseInt(redbox.style.width, 10);
    toggle ? w++ : w--;
    redbox.style.width = w + 'px';
    if (w == 100 || w == 50){          
      toggle = !toggle;
      clearInterval(poller);
    }
    if (w == 80)
      log(redbox.style.width);
  }, 20);
} 

function log(args){
  console.log(args);
}

fiddlers: https://jsfiddle.net/2mkxx6f0/4/

simon
  • 854
  • 1
  • 9
  • 23
-1

please check the code it is not for 80% it is for >80px

var redbox = document.querySelector("#redbox");
var coolbutton = document.querySelector("#coolbutton");
coolbutton.addEventListener("click", animator);
function animator() {
var a= Number("50");// increasing by 50 px
var b=Number(redbox.style.width.slice(0, -2));

  if (b <= 80) {
  var c=b+a+"px";
  
   redbox.style.width =c; 
   redbox.style.transition = "2s";
  } 
  else {
   alert("hii")
  }
} 
#redbox {
  background: red;
  height: 50px;
  width: 50px;
}
<body>
<div id="redbox"></div>
<button id="coolbutton">click</button>
</body>
SF..MJ
  • 862
  • 8
  • 19