I'm trying to change a URL for a image on scroll which i can do using this jQuery with a new image which is only displayed on scroll named scroll.png.
$( '.div img' ).attr( 'src',"scroll.png" );
} else {
$( '.div img' ).attr( 'src',"no-scroll.png" );
}
Works fine however, i need to remove it when i scroll back up which i can do using this :
$( '.div img' ).attr( 'src',"no-scroll.png" );
However, what i want to know is can i use another method to display the original image rather than add it back in the jQuery because its already added using PHP code so i don't want to ad it back using jQuery.
I was thinking something like this :
$( '.div img' ).attr( 'src',"scroll.png" );
} else {
$( '.div img' ).removeAttr( 'src',"no-scroll.png" );
}
But when i use removeAttr it removes the default image which is added using PHP code so maybe i need to use something like return.
Update : The default html includes a attribute for loading, maybe this can be used in the jQuery to return this image when the user scrolls back up?
<img src="scroll.png" loading="lazy">
What you want is DOM changes which can't be achieved through PHP, client side needs javascript/jquery.
You can approach this in multiple ways through jquery.
1- Have 2 images, one has class/id noscroll and the other has scroll. Initially one of them is hidden(by adding display:none in style attr or .hide() in jquery) and the other is shown. When you scroll you switch their display value.
<div class="div">
<img src="no-scroll.png" id="no-scroll">
<img src="scroll.png" id="scroll" style="display: none">
</div>
<script type="text/javascript">
if(someScrollEvent){
$('.div #scroll').show();
$('.div #no-scroll').hide();
} else {
$('.div #scroll').hide();
$('.div #no-scroll').show();
}
</script>
2- Through PHP when loading the image and setting their src, set an extra attr say "initial-src" equals the initial src for the image, then when you change the src to no scroll and want the original src back you set it as the initial-src attr value.
<div class="div">
<img src="no-scroll.png" initial-src="no-scroll.png">
</div>
<script type="text/javascript">
if(someScrollEvent){
$('.div img').attr('src',"scroll.png");
} else {
$('.div img').attr('src',$('.div img').attr("initial-src"));
}
</script>