Search code examples
javascriptjqueryparticles

How Do I Repel My Mouse From These Particles


So I have these particles on my site, and it's all Js. However, what I want to do, as it's interacting with the images behind it causing them to not be clickable, is to repel the particles when I move my mouse near them.

I have the code for the particles below, along side the body being black as the particles are only viewable in darkened images.

https://jsfiddle.net/sarumonin/60e1dmr5

function Particle() {
this.path = 'http://files.enjin.com/692771/Particles/';
this.images = ['particle1.png', 'particle2.png', 'particle3.png', 'particle4.png'];

//  Randomly Pick a Particle Model
    this.image = this.images[randomInt(this.images.length)];
    this.file = this.path + this.image;

//  Create a Particle DOM
    this.element = document.createElement('img');

    this.speed().newPoint().display().newPoint().fly();
};

//  Generate Random Speed
Particle.prototype.speed = function() {
    this.duration = (randomInt(10) + 5) * 1100;

    return this;
};
//  Generate a Random Position
Particle.prototype.newPoint = function() {
    this.pointX = randomInt(window.innerWidth - 100);
    this.pointY = randomInt(window.innerHeight - 100);

    return this;
};
//  Display the Particle
Particle.prototype.display = function() {
    $(this.element)
        .attr('src', this.file)
        .css('position', 'absolute')
        .css(' pointer-events', 'none')
        .css('top', this.pointY)
        .css('left', this.pointX);
    $(document.body).append(this.element);

    return this;
};

//  Animate Particle Movements
Particle.prototype.fly = function() {
    var self = this;
    $(this.element).animate({
        "top": this.pointY,
        "left": this.pointX,
    }, this.duration, 'linear', function(){
        self.speed().newPoint().fly();
    });
};

function randomInt(max) {
//  Generate a random integer (0 <= randomInt < max)
    return Math.floor(Math.random() * max);
}

$(function(){
    var total = 50;
    var particles = [];

    for (i = 0; i < total; i++){
        particles[i] = new Particle();
    }
});

Solution

  • Following is not the solution you are asking for ... but it solves your problem anyway :)

    Change in one JS-function, like this:

    //  Display the Particle
    Particle.prototype.display = function() {
        $(this.element)
            .attr('src', this.file)
            .attr('class', 'ParticleNoMouse')
            .css('top', this.pointY)
            .css('left', this.pointX);
        $(document.body).append(this.element);
        return this;
    };
    

    ... and add this to your CSS-file:

    .ParticleNoMouse {
        position:absolute;
        -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
        user-select:none;
        pointer-events:none;
    }