Prevent Overlap in Dynamically Created Divs in JQuery - javascript

I am currently working on a webpage where an array of draggable images appear in random positions over time. I would like to prevent the newly created divs from overlapping as well as create a limit to how many new divs appear.
Below is the current code That I have;
var Images = ['https://material.io/icons/static/images/icons-180x180.png', 'https://iconscout.com/ms-icon-310x310.png', 'https://maxcdn.icons8.com/Share/icon/Food//cherry1600.png', 'https://lh3.googleusercontent.com/Ax2wQYxjDITuZEpc6K9EDYPG7C839tb4PApia4Tmf18u8XehB-twqhVgDVPgxxExkr4=w300',
'https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-256.png',
'http://files.softicons.com/download/game-icons/super-mario-icons-by-sandro-pereira/ico/Mushroom%20-%201UP.ico'],
screenWidth,
screenHeight;
$(document).ready(function() {
screenWidth = $(window).width();
screenHeight = $(window).height();
$(window).on('resize', function(){
screenWidth = $(window).width();
screenHeight = $(window).height();
})
setInterval(function () {
var x = Math.random() * screenWidth,
y = Math.random() * screenHeight;
addDiv(x, y);
}, 2000);
});
function addDiv(x,y) {
var randImageIndex = Math.floor( (Math.random() * (Images.length - 1) ) );
var Image = Images[randImageIndex];
var newDiv = $('<div class="object"><img src=' + Image + ' height="100" width="100"></div>').css({top:x,left:y});
$('body').append(newDiv);
newDiv.draggable();
newDiv.on('click', function() {
$(this).remove();
})
}
Any suggestions would be greatly appreciated!

Related

Create divs in random places

I wish to create a div and position it in random places on the screen every 2 seconds. How would I accomplish this using PHP or Javascript? I am ok with using things like CSS.
div:
var blueMass = document.createElement('div');
blueMass.style.position = "absolute";
blueMass.innerHTML = "<img src='./pic/bluemass.png' height='35' width='35' />";
blueMass.id = "bluemass";
blueMass.className = "bluemass";
// my timer
window.setInterval(function(){
// Create the divs in here
}, 3000);
<div class="bluemass" id="bluemass">
<img src='./pic/bluemass.png' height='35' width='35' />
</div>
// no jQuery
$=document.querySelector.bind(document); // create selector
setInterval(function(){
s=$('div').style;
s.top=Math.random()*window.innerWidth+'px'; // multiply random (0..1) value by window height (you may want to subtract div height)
s.left=Math.random()*window.innerHeight+'px'; // ... height ...
},2000)
div{position:fixed}
<div>div</div>
// with jQuery
setInterval(function () {
$('#mydiv').css({
top: Math.random() * ($(window).height() - $('#mydiv').height()) + 'px', // multiply random .width(0..1) value by window height minus div height
left: Math.random() * ($(window).width() - $('#mydiv').width()) + 'px'
})
}, 2000)
#mydiv{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">div</div>
Just get width and height of document and use that to generate random number. You already have created the element in html, so no need to redo all that in JS.
In your specs you wanted every 2 seconds, so that would be 2000 ms in your timer.
In your timer function you would simply add the left and top of element with the new random numbers.
var blueMassElement = document.getElementById('bluemass');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
window.setInterval(function() {
// Create the divs in here
currentTop = Math.floor(Math.random() * documentHeight) + 1;
currentLeft = Math.floor(Math.random() * documentWidth) + 1;
blueMassElement.style.top = currentTop + "px";
blueMassElement.style.left = currentLeft + "px";
}, 2000);
#bluemass {
position:absolute;
}
<div id="bluemass" class="bluemass">
<img height="35" width="35" src='http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437' />
</div>

How to make script resize images and divs on window resize and orientation change

I am currently using the following javascript to resize an image to the size of it's parent, while maintaining aspect ratio and keeping the parent div square. So i have a square box with a rectangle stretched to either the max width or max height depending on orientation. This works great on first load however I cannot get the images and divs to resize on page orientation change or resize to work. Any ideas. I have tried using the window.resize and window.orientation listeners.
Original code was from:
Scale, crop, and center an image...
var aspHt = $('.aspectcorrect').outerWidth();
$('.aspectcorrect').css('height', aspHt + 'px').css('width', aspHt + 'px');
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = {
width : 0,
height : 0,
fScaleToTargetWidth : true
};
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
} else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
} else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
function RememberOriginalSize(img) {
if (!img.originalsize) {
img.originalsize = {
width : img.width,
height : img.height
};
}
}
function FixImage(fLetterBox, div, img) {
RememberOriginalSize(img);
var targetwidth = $(div).width();
var targetheight = $(div).height();
var srcwidth = img.originalsize.width;
var srcheight = img.originalsize.height;
var result = ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox);
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function(index, div) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, this, img);
});
}
window.onload = function() {
FixImages(true);
};
Call .resize() after $(window).resize():
$(window).resize( function(){
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#landscape").css('display','none');
} else {
// Portrait
$("#landscape").css('display','block');
$("#landscape").click(function(){
$(this).hide();
});
}
}).resize();
I figured out what I was missing. The first bit of javascript is setting the style of height and width. When recalling the .outerHeight it was still using the inline style to calculate the width, and hence not resizing the div. I simply used .removeAttr('style') to remove that property first and then did the resize. Working now. I simply used $(window).on("resize", resizeDiv) and wrapped my resizing into a function named resizeDiv
function resizeDiv() {
var asp = $('.aspectcorrect');
asp.removeAttr("style");
var aspHt = asp.outerWidth();
asp.css('height', aspHt + 'px').css('width', aspHt + 'px');
FixImages(true);
}

How to adjust page to scroll to center on clicking on carousel?

I'm trying to get it so that when you click on the carousel, the page will adjust to have the carousel in the center. This website (http://studionewwork.com/) shows this when you click on their carousel. I'm still learning about Jquery so I'm not yet adept at commands yet.
http://jsfiddle.net/8bJUc/614/
$(document).ready(function () {
$("#owl-demo").owlCarousel({
navigation: true,
pagination: true,
lazyLoad: true
});
});
$('.owl-demo').on('click', function(e) {
var el = $( e.target.getAttribute('href') );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
var speed = 700;
$('html, body').animate({scrollTop:offset}, speed);
});
Hey I updated your fiddle to make it work: http://jsfiddle.net/8bJUc/649/
Basically you are using $(".owl-demo") as if it's a class, but it's an ID. Then the onClick function tries to get the clicked element but fails doing so.
var el = $( e.target.getAttribute('href') );
This line basically says:
Get the href-attribute from the clicked element and use jQuery to locate any elements matching the href attribute. I removed this since you don't specify the href attribute anywhere.
$('.owl-carousel').on('click', function(e) {
var el = $(".lazyOwl", this);
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
var speed = 700;
$('html, body').animate({scrollTop:offset}, speed);
});
Please note that the example carousel you posted doesn't work as expected on my Macbook Air 11''. The carousel jumps around whenever I click on it.

Making a function work in all divs with the same class using jquery

I have a responsive div (.container) that contains a row of nested divs (.imgWrapper) that each contain an image (.imgWrapper img). The purpose of the following code is to make all images the same height while still fitting in one row in the container despite all images being a different proportion to one another (i.e. landscape and portrait)
var totalHeight = 100;
var totalWidth = 1;
$('.imgWrapper').each(function(){
totalWidth += $(this).outerWidth();
});
var containerWidth = $('.container').width();
var ratio = totalWidth / totalHeight;
var containerHeight = containerWidth / ratio;
$('.container').css('height',containerHeight + "px");
$('.imgWrapper img').css('height',containerHeight + "px");
var newTotalWidth = 0;
$('.imgWrapper').each(function(){
newTotalWidth += $(this).outerWidth();
});
$('.container').css('width',newTotalWidth + "px");
});
});
This all works great if there is only one div with the class '.container', however as soon as I add div with the same class, the function is applied to all images instead of images in each '.container' div. How to I apply this function to each '.container' div one at a time?
Here is a jsfidde example: http://jsfiddle.net/tbbeqcqb/
Not 100% sure what you are trying to achieve, but I think it's this;
$(window).bind("load", function() {
var totalHeight = 100;
$('.container').each(function(){
var totalWidth = 1;
$(this).children().filter('.imgWrapper').each(function(){
totalWidth += $(this).outerWidth();
});
var containerWidth = $(this).width();
var ratio = totalWidth / totalHeight;
var containerHeight = containerWidth / ratio;
$(this).css('height',containerHeight + 'px');
var newTotalWidth = 0;
$(this).children().filter('.imgWrapper').each(function(){
$(this).children('img').css('height',containerHeight + 'px');
newTotalWidth += $(this).outerWidth();
});
$(this).css('width',newTotalWidth + 'px');
});
});

making a function works on specific widths

I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.

Categories