Search code examples
javascripthtmlscript-tag

One of Multiple Scripts in HTML Sheet Not Working


I am trying to have multiple scripts run in my html sheet, and it seems to not be working. All the other scripts work except for the script for the blinking function. I don't see what the problem is. Can you find the issue with my code? Thanks in advance!

Here is my code below:

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: coral;
    color: white;
}

.text2{
  color: white;
  width: 100px;
  float: right;
  padding-top: 10px;
}


</style>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".btn1").on('click',function(){
     $("p").hide();
     $(".text2").hide()
     $('body').css("background", "black");      
    });

});
</script>

<script>

//blink
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);

function toggle() {
    if(shown) {
        element.hide();
        shown = false;
    } else {
        element.show();
        shown = true;
    }
}
</script>

</head>
<body>

<p>This is a paragraph.</p>

</div>
     <div class="text2">
     -- : --
</div>  
<button class="btn1">online</button>



</body>
</html>

Solution

  • The second script must be inside a JQuery function.

    $(document).ready(function(){
    var element = $(".text2");
    var shown = true;
    setInterval(toggle, 500);
    
    function toggle() {
        if(shown) {
            element.hide();
            shown = false;
        } else {
            element.show();
            shown = true;
        }
    }
        });