Home Javascript do something before alert
Reply: 2

Javascript do something before alert

adeneo
1#
adeneo Published in 2016-11-21 16:20:17Z

I want to change the color and alert a message when a button is clicked.

function colorChange() {
  document.getElementById('word').style.color = "red";
  alert("color changed!");
}

I cannot change the color at the same time with an alert.

adeneo
2#
adeneo Reply to 2016-11-21 16:22:38Z

Wrap the alert in a timeout

function colorChange() {
  document.getElementById('word').style.color = "red";
  setTimeout(function() {
  	alert("color changed!");
  },10)
}
<div id="word">
Word .....
</div>
<br />
<button onclick="colorChange()">
Change color
</button>

The browser doesn't have time to repaint before the alert fires, by using a timeout you delay the alert until the next tick, when the repaint has completed.

Artur Hovhannisyan
3#
Artur Hovhannisyan Reply to 2016-11-21 16:29:09Z

$(document).ready(function()
{
  $('#myButton').click(function(){
    $('#word').css("color","red");
    
     setTimeout(function() {
  	alert("color changed!");
  },10)
  })
  
})
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
  <p id="word">word</p>
   <button id="myButton" >change color</button>  
 <body>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.414788 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO