Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My javascript function works only after I hard refresh the page

I know that there are multiple questions about this same problem, but I couldn't find an answer in any of them. I'm using javascript to activate hover on other elements. The javascript code works fine but it only works after I hard refresh the page, CTRL + R. If I go to the page normally it won't work.

JS:

      $(function() {
      $('#faqBg').hover(function() {
      $('#spanContainer').css('background', 'rgb(0, 0, 0, 0.6');
      }, function() {
        // on mouseout, reset the background colour
      $('#spanContainer').css('background', '');
      });
    });
.image-wrapper {
 position: relative;
}
 
 #faqBg { 
    background: linear-gradient(-45deg,rgba(0,0,0,.5),rgba(0,0,0,.5)),url(https://images.pexels.com/photos/1239162/pexels-photo-1239162.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500);
    padding: 60px 0px;
    display: block;
    background-size: cover;
    background-repeat: no-repeat;
    }
    
 #spanContainer {
    color: #fff;
    width: 100%;
    text-align: center;
    padding: 20px 0px;
    }
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="image-wrapper">

<div id="faqBg">

<div id="spanContainer">

Hover trigger

</div>

</div>

</div>

This is the code Im using, here when I do it everything seems allright, but on the website it doesnt. I tried adding $(document).ready and $(document).load but it didnt worked.

like image 869
Freelancer Help Avatar asked Apr 19 '26 16:04

Freelancer Help


2 Answers

This is happening because of cache.

Add version to you javascript file on loading:

<script src="file.js?v=1"></script> Increment the v parameter on each change you want to see. If your page is generated dynamically you can set to v a timestamp value, depends on the backend language you are using.

Another solution is to use these meta tags:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
like image 74
Andrei Todorut Avatar answered Apr 22 '26 04:04

Andrei Todorut


Use CSS instead:

 #faqBg:hover #spanContainer { 
       background: rgba(0,0,0,0.6);
 }
like image 40
Devashish Avatar answered Apr 22 '26 05:04

Devashish