Search code examples
javascriptjquerycssbackground-positiononmousemove

jQuery on mouse move target selects all similar elements


I have (for example) 6 elements, all with same classes and different content. All of them also have backgrounds that are slightly zoomed in. I need their backgrounds to move accordingly when the mouse hovers on them. My problem - all backgrounds move once I hover on a single element. Any help?
Here's my code:

HTML (of a single element):

<a href="/" class="project" style="background-image: url('link_to_image');"><p>Project</p><span>Description</span></a>

CSS (again, single element):

.project {
    position: relative;
    display: inline-block;
    margin: 10px;
    height: 400px;
    width: 400px;
    background: #b0bec5;
    color: #fff;
    text-decoration: none;
    box-shadow: inset 0px 0rem 0px rgba(0,0,0,0), inset 0px -50px 100px -40px rgba(0,0,0,0.6);
    transition: box-shadow .5s ease-in-out;
    overflow: hidden;
    float: left;
    white-space: initial;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

.project p {
    position: absolute;
    bottom: 2%;
    left: 2%;
    font-size: 40px;
    font-family: "Josefin Slab";
    font-weight: bold;
    transition: all .46s ease-in-out;
    transition-delay: .02s;
    z-index: 1;
}

.project span {
    display: block;
    position: absolute;
    top: 100%;
    left: 2%;
    font-size: 20px;
    font-family: "Raleway";
    transition: all .46s ease-in-out;
    transition-delay: .02s;
    z-index: 1;
}

.project:hover p {
    bottom: 88%;
}

.project:hover span {
    top: 15%;
}

.project:hover {
    box-shadow: inset 0px -30rem 0px rgba(0,0,0,0.4);
}

JS:

$(".project").on("mousemove", function(e){
    x = (e.pageX - e.target.offsetLeft * 1.5) / 4;
    console.log(x);
    $(".project").css('background-position-x', x + 'px');
});

Solution

  • Use this!

    $(".project").on("mousemove", function(e){
        x = (e.pageX - e.target.offsetLeft * 1.5) / 4;
        console.log(x);
        $(this).css('background-position-x', x + 'px'); //"this" refers to the .project elem that the event is occurring on.
    });