I am looking to write some code that will subtly move the background of a div based on x axis mouse movements. I am currently using .mousemove and the background-position property to move the background image. I had to move the background a little depending on the window size so that it would not go off the page. I set up some if statements to handle this but the background position does not update when the window is resized. It only works when the page is reloaded completely- then it reads the if statements again and the background is positioned properly. The background position is 23% 50% for media queries that correspond to smaller windows, and 40% 50% for media queries that correspond to larger window sizes. Any ideas as to how I can modify the code to make the background position update in real time when the window is resized?
Thank you!
$( document ).ready(function(){
if ($(".container").css("background-position")=="23% 50%")
{
$( document ).mousemove(function( event ) {
var m = event.pageX;
var q = 23 + m/200;
$(".container").css({"background-position": q + "% 50%"});
$(".andServices").text(q);
});
}
else if ($(".container").css("background-position")=="40% 50%")
{
$( document ).mousemove(function( event ){
var z = event.pageX;
var t = 40 + z/200;
$(".container").css({"background-position": t + "% 50%"});
$(".creativeProducts").text(t);
});
}
});
<div class="container">
<div class = "mobileBG"></div>
<div class="textContainer">
<p class="creativeProducts">Creative Products</p>
<p class = "andServices">And Services</p>
<p class = "ebaySales">eBay Sales</p>
<p class = "seoServices">SEO Services</p>
<p class = "webDesign">Web Design</p>
<p class = "photography">Photography</p>
</div>
</div>
.container{
width:100%;
position:relative;
top:0;
bottom:0;
left:0;
right:0;
height:750px;
background-image:url(images/frontCoverImage.gif);
background-size:cover;
background-repeat:no-repeat;
background-position:23% 50%;
}
3
Answers
Basically if you wish to catch browser resize you would need to use the following.
Hope this helps.
Try this
Jquery’s .resize() basically works whenever the user resize the window/browser
@Norman is right you’ll need to use JQuery’s .resize() for this.
However you can wrap .resize() and .load() together using the .on() event listener.