1

I would like to resize my div's (#bg) background-image by mousemove function. I found a couple of "solutions" on stackoverflow but non of them were 100% what I want. I tried it with adding h1 to see whether if mousemove is working, its working. I also tried it with .css('transform', 'scale('+ myMouse/2 +')'); but it sometimes scales out of the image when I hover the most right of the screen. I need to use background-size and calc() function together. I guess i have a syntax problem but couldnt figured out EDIT: I also tried with 'background-size': calc(100% '+myMouse/2+') colon(:) gives syntax error

Here is my CSS and JavaScript code;

section #bg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url(../img/bg.jpg);
    background-size: 100%;
}


     $(document).ready(function(){
        $(document).mousemove(function(e){
            var myMouse = e.pageX; 
            //$('#myh1').text("value of x is : "+ myMouse + "."); this worked for h1 tag
            $('#bg').css('background-size', 'calc(100% + '+myMouse/2+')'); 
        })
    })
wasilikoslow
  • 1,411
  • 1
  • 9
  • 13

1 Answers1

1

You have to specify unit in calc function in css.

$(document).ready(function(){
    $(document).mousemove(function(e){
        var myMouse = e.pageX; 
        $('#bg').css('background-size', 'calc(100% + ' + myMouse/2 + 'px)'); 
    })
})
#bg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background-image: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
    background-size: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bg"></div>
Mahdi Aslami Khavari
  • 1,755
  • 15
  • 23