Absolute elements particles overlapping other elements issue

475 views Asked by At

I placed this nifty particle script in my page for an interesting look and also to play with more intricate JS but have found that some of the particles which I made larger to to look like bokeh motes are floating over the image links causing them to be un-clickable which, while not a huge problem can be annoying.

I'm wondering how to modify this script to have the particles be behind the image button links. There is no css except in the one section where it is applied by the script in the Display the particle section.

On a side note, I tried giving the image and link a z-index of 10000 just to see if that would help but still no go.

<script type="text/javascript">
  function Particle() {
   this.path = '../static/images/';
   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('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 = 30;
var particles = [];

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

There are 1 answers

6
Roko C. Buljan On BEST ANSWER

Use .prepend (instead of .append)

$(document.body).prepend( this.element );

that way your absolute particles will be positioned underneath other positioned page elements due to the natural Z order DOM precedence.

From the above you can understand that you also need to add position to your main page wrapper in order to make this work:

http://jsbin.com/cizut/1/edit?html,css,js,output


Conclusion:

#mainPageWrapper{
  position:relative;
  /* .....other styles */
}

$(document.body).prepend( this.element );