Responsive Slider Script - javascript

I'm trying to add a responsive slider to my website and am having a couple of issues. The biggest is the size of the outside container. On desktop, the actual size of the slider should be 680 x 380. As it stands, I have major margins on either side of the slider and really am not sure how to get rid of them. I'm sure this is easy for most of you but, I can't figure it out. Secondly, is there an easy way to have the images appear in random order? Any help would be greatly appreciated. Thanks very much
Here is my test page for the slider: https://www.realtimehockey.net/testing.html
I need the slider to fill the entire container much like my current slider here: https://www.realtimehockey.net
HTML
<div id="slidy-container">
<figure id="slidy">
<img src="https://i.imgur.com/iVhs269.png" width="680" height="380" alt="Black-Biscuit Hockey Outfitters" data-caption="Black-Biscuit Hockey Outfitters">
<img src="https://i.imgur.com/cqMgCFa.png?2" width="680" height="380" alt="All Black Hockey Sticks" data-caption="All Black Hockey Sticks" >
<img src="https://i.imgur.com/WhSLIsE.png?1" width="680" height="380" alt="OneHockey Guinness World Record" data-caption="OneHockey Guinness World Record">
<img src="https://i.imgur.com/ZQ2KecX.png" width="680" height="380" alt="Planet Hockey Camps" data-caption="Planet Hockey Camps">
<img src="https://i.imgur.com/9x1H8wq.png" width="680" height="380" alt="OneHockey Tournaments" data-caption="OneHockey Tournaments">
<img src="https://i.imgur.com/1kzo8hS.jpg" width="680" height="380" alt="ScoreStream" data-caption="ScoreStream">
</figure>
</div>
JS
var cssSlidy = function(newOptions) {
var options = (function() {
var mergedOptions = {},
defaultOptions = {
timeOnSlide: 4,
timeBetweenSlides: 1,
slidyContainerSelector: '#slidy-container', // name of slider container
slidySelector: '#slidy', // name of slider
slidyDirection: 'left', // options: left, right
fallbackFunction: function() {},
cssAnimationName: 'slidy',
captionSource: 'data-caption', // options: data-caption, alt, none
captionBackground: 'rgba(0,0,0,0.8)',
captionColor: '#fff',
captionFont: 'anton',
captionPosition: 'bottom', // options: top, bottom
captionAppear: 'slide', // options: slide, perm, fade
captionSize: '1.3rem',
captionPadding: '.6rem'
};
for (var option in defaultOptions) mergedOptions[option] = defaultOptions[option];
for (var option in newOptions) mergedOptions[option] = newOptions[option];
return mergedOptions;
})(),
CS = this;
CS.animationString = 'animation';
CS.hasAnimation = false;
CS.keyframeprefix = '';
CS.domPrefixes = 'Webkit Moz O Khtml'.split(' ');
CS.pfx = '';
CS.element = document.getElementById(options.slidySelector.replace('#', ''));
CS.init = (function() {
// browser supports keyframe animation w/o prefixes
if (CS.element.style.animationName !== undefined) CS.hasAnimation = true;
// browser supports keyframe animation w/ prefixes
if (CS.hasAnimation === false) {
for (var i = 0; i < CS.domPrefixes.length; i++) {
if (CS.element.style[CS.domPrefixes[i] + 'AnimationName'] !== undefined) {
CS.pfx = domPrefixes[i];
CS.animationString = pfx + 'Animation';
CS.keyframeprefix = '-' + pfx.toLowerCase() + '-';
CS.hasAnimation = true;
// determines CSS prefix required for CSS animations
break;
}
}
}
if (CS.hasAnimation === true) {
var images = CS.element.getElementsByTagName("img"),
L = images.length,
fig = document.createElement('figure'),
who, temp;
while(L) {
temp = fig.cloneNode(false);
who = images[--L];
// wraps all images in the slider with <figure> tags
if (options.captionSource!=="none")
caption = who.getAttribute(options.captionSource);
who.parentNode.insertBefore(temp, who);
if (caption !== null) {
content = document.createElement('figcaption');
content.innerHTML = caption;
// places captions in each <figure> element, if required
}
temp.appendChild(who);
if (caption !== null) {
temp.appendChild(content);
}
}
var figs = CS.element.getElementsByTagName("figure");
var firstFig = figs[0]; // get the first figure inside the "slidy" element.
figWrap = firstFig.cloneNode(true); // copy it.
CS.element.appendChild(figWrap); // add the clone to the end of the images
var imgCount = images.length, // count the number of images in the slide, including the new cloned element
totalTime = (options.timeOnSlide + options.timeBetweenSlides) * (imgCount - 1), // calculate the total length of the animation by multiplying the number of _actual_ images by the amount of time for both static display of each image and motion between them
slideRatio = (options.timeOnSlide / totalTime) * 100, // determine the percentage of time an induvidual image is held static during the animation
moveRatio = (options.timeBetweenSlides / totalTime) * 100, // determine the percentage of time for an individual movement
basePercentage = 100 / imgCount, // work out how wide each image should be in the slidy, as a percentage.
position = 0, // set the initial position of the slidy element
css = document.createElement("style"); // start marking a new style sheet
// creating css style tag
css.type = "text/css";
css.id = options.slidySelector.replace('#', '') + "-css";
css.innerHTML += options.slidyContainerSelector + " { overflow: hidden; }\n";
css.innerHTML += options.slidySelector + " { text-align: left; margin: 0; font-size: 0; position: relative; width: " + (imgCount * 100) + "%; }\n"; // set the width for the inner slider container
css.innerHTML += options.slidySelector + " figure { float: left; margin: 0; position: relative; display: inline-block; width: " + basePercentage + "%; height: auto; }\n"; // set the width and size pf the inner <figure> elements
css.innerHTML += options.slidySelector + " figure img { width: 100%; }\n";
css.innerHTML += options.slidySelector + " figure figcaption { position: absolute; width: 100%; background-color: " + options.captionBackground + "; color: " + options.captionColor + "; font-family: " + options.captionFont + ";";
var captions = document.getElementsByTagName("figcaption");
var captionHeight = captions[0].offsetHeight*2 + parseInt(window.getComputedStyle(captions[0]).fontSize, 10);
if (options.captionPosition == "top") {
switch (options.captions) {
case 'fade':
css.innerHTML += " top: 0; opacity: 0;";
break;
case 'slide':
css.innerHTML += " top: -"+captionHeight+"px; ";
break;
default:
css.innerHTML += " top: 0;";
}
} else {
switch (options.captionAppear) {
case 'fade':
css.innerHTML += " bottom: 0; opacity: 0;";
break;
case 'slide':
css.innerHTML += " bottom: -"+captionHeight+"px; ";
break;
default:
css.innerHTML += " bottom: 0;";
}
}
css.innerHTML += " font-size: " + options.captionSize + "; padding: " + options.captionPadding + "; " + keyframeprefix + "transition: .5s; }\n";
css.innerHTML += options.slidySelector + ":hover figure figcaption { opacity: 1; ";
if (options.captionPosition == "top") { css.innerHTML += " top: 0px;"; }
else { css.innerHTML += " bottom: 0px;"; }
css.innerHTML += " }\n";
css.innerHTML += "#" + keyframeprefix + "keyframes " + options.cssAnimationName + " {\n";
if (options.slidyDirection == "right") {
for (i = imgCount - 1; i > 0; i--) { //
position += slideRatio; // make the keyframe the position of the image
css.innerHTML += position + "% { left: -" + (i * 100) + "%; }\n";
position += moveRatio; // make the postion for the _next_ slide
css.innerHTML += position + "% { left: -" + ((i - 1) * 100) + "%; }\n";
}
} else { // the slider is moving to the left
for (i = 0; i < (imgCount - 1); i++) { //
position += slideRatio; // make the keyframe the position of the image
css.innerHTML += position + "% { left: -" + (i * 100) + "%; }\n";
position += moveRatio; // make the postion for the _next_ slide
css.innerHTML += position + "% { left: -" + ((i + 1) * 100) + "%; }\n";
}
}
css.innerHTML += "}\n";
css.innerHTML += options.slidySelector + " { ";
if (options.slidyDirection == "right") { css.innerHTML += "left: " + imgCount*100+"%" }
else { css.innerHTML += "left: 0%; " }
css.innerHTML += keyframeprefix + "transform: translate3d(0,0,0); " + keyframeprefix + "animation: " + totalTime + "s " + options.cssAnimationName + " infinite; }\n"; // call on the completed keyframe animation sequence
// place css style tag
if (options.cssLocation !== undefined) options.cssLocation.appendChild(css);
else document.body.appendChild(css);
} else {
// fallback function
options.fallbackFunction();
}
})();
}
cssSlidy();
CSS
body {
background: #ffffff;
}
#slidy-container {
width: 70%;
margin: 0 auto;
overflow: hidden;
}

Related

Organizing buttons in div using only JavaScript

I need help with organizing this gallery to look like this:
I tried everything I know with positions (absolute and relative), bottoms, margins... but I can't seem to organize it properly.
This popup div needs to occupy 80% of page height and 80% of the page width, and images shouldn't break out of div.
I am not allowed to change HTML or to add CSS. Everything needs to be written inside the JS file.
Here is my code:
$(document).ready(function() {
var images = $('div[title ="London gallery"]').children('img').map(function() {
return $(this).attr('src')
}).get();
var description = $('div[title ="London gallery"]').children('p').map(function() {
return $(this).text();
}).get();
$('div[title ="London gallery"]').hide();
var gallery_lndn = document.createElement('button');
gallery_lndn.id = 'btn_London';
gallery_lndn.innerHTML = 'Look at the galery!';
document.body.appendChild(gallery_lndn);
document.getElementById('btn_London').onclick = function() {
show_pictures(images, description);
}
function show_pictures(images, description) {
function popUp() {
var index = 0;
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'div_popup';
popup.style.background = "#2F4F4F";
popup.style.position = "absolute";
popup.style.top = "0px";
popup.style.left = "0px";
popup.style.right = "0px";
popup.style.margin = "100px auto";
popup.style.height = "80%";
popup.style.width = "80%";
var cancelButton = document.createElement('button');
cancelButton.innerHTML = 'x';
cancelButton.id = 'btn_cancelButton';
cancelButton.style.background = "red";
cancelButton.style.border = "none";
cancelButton.style.display = "inline-block";
cancelButton.style.fontSize = "16px";
cancelButton.style.padding = "15px 20px";
cancelButton.style.float = "right";
cancelButton.style.top = "0";
cancelButton.onclick = function(e) {
popup.parentNode.removeChild(popup)
};
var previousButton = document.createElement('button');
previousButton.innerHTML = '<<';
previousButton.style.background = "#32CD32";
previousButton.style.border = "none";
previousButton.style.display = "inline-block";
previousButton.style.fontSize = "16px";
previousButton.style.padding = "15px 32px";
previousButton.style.position = "absolute";
previousButton.style.float = "left";
previousButton.style.bottom = "0";
previousButton.onclick = function() {
index = (index == 0) ? images.length - 1 : index - 1;
console.log(index);
updateImage();
}
var nextButton = document.createElement('button');
nextButton.innerHTML = '>>';
nextButton.style.background = "#32CD32";
nextButton.style.background = "#32CD32";
nextButton.style.border = "none";
nextButton.style.display = "inline-block";
nextButton.style.fontSize = "16px";
nextButton.style.padding = "15px 32px";
//nextButton.style.position = "absolute";
nextButton.style.float = "right";
nextButton.style.bottom = "0";
nextButton.onclick = function() {
index = (index == images.length - 1) ? 0 : index + 1;
console.log(index);
updateImage();
}
function updateImage() {
var img = new Image();
img.src = images[index];
img.style.margin = "auto";
img.style.position = "relative";
img.style.display = "block";
console.log(img);
$("#div_popup").html("");
if (index == 0) {
previousButton.style.background = "#A9A9A9";
//previousButton.disabled = "true";
} else if (index == images.length - 1) {
nextButton.style.background = "#A9A9A9";
//nextButton.disabled = "true";
} else {
//nextButton.disabled = "false";
//previousButton.disabled = "false";
previousButton.style.background = "#32CD32";
nextButton.style.background = "#32CD32";
}
popup.appendChild(previousButton);
popup.appendChild(nextButton);
popup.appendChild(cancelButton);
var message = document.createElement('span');
//message.style.position = "absolute";
message.style.bottom = "0";
message.innerHTML = "Picture " + (index + 1) + "/" + images.length + "<br>" + description[index];
img.onload = function() {
popup.appendChild(message);
popup.appendChild(img);
document.body.appendChild(popup);
};
}
updateImage();
}
popUp();
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script src="gallery.js"></script>
</head>
<body>
<h1>London</h1>
<div class="gallery" title="London gallery">
<img src="https://cdn.londonandpartners.com/visit/general-london/areas/river/76709-640x360-houses-of-parliament-and-london-eye-on-thames-from-above-640.jpg">
<p data-target="https://cdn.londonandpartners.com/visit/general-london/areas/river/76709-640x360-houses-of-parliament-and-london-eye-on-thames-from-above-640.jpg">
Description 1.
</p>
<img src="https://news.itu.int/wp-content/uploads/2018/07/london-min-e1530887248858.jpg">
<p data-target="https://news.itu.int/wp-content/uploads/2018/07/london-min-e1530887248858.jpg">
Description 2.
</p>
</div>
</body>
</html>
You can update the button positions according to the image. Call below method inside the updateImage method just before closing.
function updatePositions(){
// absolute position for all buttons
$('#div_popup > button').css({'position': 'absolute', 'float':'none', 'z-index': 1});
// get image bottom position
let buttonTopPos = ($('#div_popup > img').offset().top + $('#div_popup > img').height()) - $('#div_popup').offset().top + 20;
// get image bottom left position
let buttonLeftPos = 0;
if($('#div_popup').width() > $('#div_popup > img').width()){
buttonLeftPos = ($('#div_popup').width() - $('#div_popup > img').width())/2
}else{
$('#div_popup > img').css({'min-width':'100%', 'max-width':'100%'});
}
// image overflow will be hidden
$('#div_popup').css('overflow', 'hidden');
// Back button position
$('#div_popup > button:nth-child(1)').css({'top': buttonTopPos, 'bottom':'auto', 'left': buttonLeftPos +'px'})
// Next button position
$('#div_popup > button:nth-child(2)').css({'top': buttonTopPos, 'bottom':'auto', 'left': (buttonLeftPos + $('#div_popup > img').width()) - 90})
// cancel button position
$('#div_popup > button:nth-child(3)').css({'top': 0, 'right': 0, left: 'auto'});
// description position
$('#div_popup > span').css({'position': 'absolute','top': buttonTopPos, 'bottom':'auto', 'left': buttonLeftPos + 90, 'width': $('#div_popup > img').width() - 90 - 90, 'text-align': 'center'})
}
Here's a layout that approximates the sample, above. For convenience, this uses JavaScript to add a <style> element to the <head>.
window.onload = () => {
const myCSS =
' body {\n' +
' width:100vw;\n' +
' height:100vh;\n' +
' position:relative\n' +
' }\n' +
' .gallery {\n' +
' background-color: darkblue;\n' +
' width: 80%;\n' +
' height: 80%;\n' +
' position: absolute;\n' +
' top: 10%;\n' +
' left: 10%;\n' +
' }\n' +
' .img-wrapper {\n' +
' background-color: transparent;\n' +
' width: calc(100% - 120px);\n' +
' height: calc(100% - 160px);\n' +
' margin: 60px;\n' +
' overflow-y: hidden;\n' +
' }\n' +
' .img-wrapper img {\n' +
' width: 100%;\n' +
' height: auto;\n' +
' }\n' +
' .btn1 {\n' +
' width: 120px;\n' +
' height: 60px;\n' +
' position: absolute;\n' +
' left: 60px;\n' +
' bottom: 30px;\n' +
' background-color: #999;\n' +
' }\n' +
' .btn2 {\n' +
' width: 120px;\n' +
' height: 60px;\n' +
' position: absolute;\n' +
' right: 60px;\n' +
' bottom: 30px;\n' +
' background-color: #999;\n' +
' }\n' +
' .btn-close {\n' +
' width: 80px;\n' +
' height: 40px;\n' +
' position: absolute;\n' +
' right: 0;\n' +
' top: 0;\n' +
' background-color: #999;\n' +
' }\n' +
' .caption {\n' +
' width: calc(100% - 409px);\n' +
' height: 60px;\n' +
' position: absolute;\n' +
' left: 192px;\n' +
' bottom: 30px;\n' +
' color: white;\n' +
' border: 1px dashed #aaa;\n' +
' text-align: center;\n' +
' padding: 0 12px;\n' +
' overflow: hidden;\n' +
' }\n';
const myStyle = document.createElement('style');
myStyle.id = 'myCSS';
myStyle.innerHTML = myCSS;
document.head.appendChild(myStyle);
}
<body>
<div class="gallery">
<div class="img-wrapper">
<img src="https://cdn.londonandpartners.com/visit/general-london/areas/river/76709-640x360-houses-of-parliament-and-london-eye-on-thames-from-above-640.jpg">
</div>
<div class="btn1">.btn1</div>
<div class="btn2">.btn2</div>
<div class="caption">.caption</div>
<div class="btn-close">.btn-close</div>
</div>
</body>

How could I add some HTML/Text into a Javascript text output? I can only seem to either only do JS or only text, not both

I am currently trying to design a scrolling command prompt with JS and HTML. Unfortunately I cannot find a way to output text and a JavaScript variable on the same line. I feel like I have tried a million things.
var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'TEST';
var java = '282828'
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function() {
if (i < text.length)
runner();
else {
textarea.append("<br>")
i = 0;
setTimeout(function() {feedbacker();}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 5;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 10 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 1000) + 1000;
count += time;
setTimeout(
function() {
if (i < output.length - 2)
feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function() {$(".load").fadeOut(1000);}, 1000000);
}
},time);
}
var output = [
"Below is a vat test",
"number" (java),
"Hello",
(java),
"Above is a test",
"Initialising...",
""];
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term">dev:~$ </pre>
</div>
This outputs correctly but any time I try to add text it fails. For example:
"number" (java),
"number", (java),
"number (java)",
"number '(java)'",
I think this output may be broken because it's a textarea. I am not sure. I would love to learn and get this figured out. Much appreciated!
var output = [
"Below is a vat test",
"number" (java),
"Hello",
(java),
"Above is a test",
"Initialising...",
""];
"number" (java) and (java) are not the correct way to display Javascript Variables.
You use simply java, or use + to concatenate two strings together such as "number" + java. You could be fancier with Template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals:
var output = [
"Below is a vat test",
`number ${java}`,
"Hello",
java,
"Above is a test",
"Initialising...",
""];
Just use concatenation (+) to append a JavaScript variable to static content.
var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'TEST';
var java = '282828'
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function() {
if (i < text.length)
runner();
else {
textarea.append("<br>")
i = 0;
setTimeout(function() {feedbacker();}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 5;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 10 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 1000) + 1000;
count += time;
setTimeout(
function() {
if (i < output.length - 2)
feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function() {$(".load").fadeOut(1000);}, 1000000);
}
},time);
}
var output = [
"Below is a vat test",
"number (" + java + ")",
"Hello",
"(" + java + ")",
"Above is a test",
"Initialising...",
""];
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term">dev:~$ </pre>
</div>

Function not get called from dynamically created html code

I'am changing the html code from javascript and want to call same function from created "div"s. but it is not called.
As you can see 'html' which is formed after function invoke also has class="screen" but created 'div's doesn't support it.
var i;
var clear = 2;
$("#container").click(function() {
var clickid = $(this).attr('id');
var left = document.getElementById(clickid).offsetLeft;
var top = document.getElementById(clickid).offsetTop;
var height = document.getElementById(clickid).offsetHeight;
var width = document.getElementById(clickid).offsetWidth;
var x = document.getElementById(clickid).value;
orient = prompt("vertical or horizontal ?");
numdiv = prompt("How many divisions should be created ?");
var divsper = [];
var html = "";
for (i = 0; i < numdiv; i++) {
per = prompt("Percentage of " + (i + 1) + "th division ?");
divsper.push(per);
}
if (orient == "vertical") {
for (i = 0; i < numdiv; i++) {
l = Math.floor(left + ((i * divsper[i] * width) / 100));
w = Math.floor((divsper[i] * width) / 100);
html = html + "<div id=" + clickid + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
}
document.getElementById(clickid).outerHTML = html;
//document.getElementById(clickid).unwrap();
}
});
* {
padding: 0px;
margin: 0px;
}
body {}
#container {
background-color: pink;
top=0%;
left=0%;
height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>
Replace '$("#container").click(function() {' this line with '$("html").on('click', '[id*=container]', function() {'.
It will work for you.
var i;
var clear = 2;
$("html").on('click', '[id*=container]', function() {
var clickid = $(this).attr('id');
var left = this.offsetLeft;
var top = this.offsetTop;
var height = this.offsetHeight;
var width = this.offsetWidth;
var x = this.value;
orient = prompt("vertical or horizontal ?");
numdiv = prompt("How many divisions should be created ?");
var divsper = [];
var html = "";
for (i = 0; i < numdiv; i++) {
per = prompt("Percentage of " + (i + 1) + "th division ?");
divsper.push(per);
}
if (orient == "vertical") {
for (i = 0; i < numdiv; i++) {
l = Math.floor(left + ((i * divsper[i] * width) / 100));
w = Math.floor((divsper[i] * width) / 100);
html = html + "<div id=" + clickid + (i + 1) + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
}
this.outerHTML = html;
//this.unwrap();
}
});
* {
padding: 0px;
margin: 0px;
}
body {}
#container {
background-color: pink;
top=0%;
left=0%;
height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>
Try using $('#container').on('click') instead. Dynamically generated html event handling is slightly different.

Absolute Center on Dynamic Elements [duplicate]

This question already has answers here:
How can I center an absolutely positioned element in a div?
(37 answers)
Closed 8 years ago.
So I have a rotator, which works good. However the master box is determined by the largest image. And all images (if smaller and such) should float in the center of the master box. However my margin edits don't seem to be doing anything in the code. Any ideas why they aren't applying?
var postimgrotator = $('.postimgrotator'),
preloader = $('#loading-images');
postimgrotator.each(function () {
this['tmp'] = '';
this.tmp2 = '';
this.postimages = new Array();
this.cur = 0;
this.count = 0;
console.log($(this));
this['postimages'] = $(this).html().trim().split(" ");
this['count'] = this['postimages'].length;
$(this).html("");
for (this['cur'] = 0; this['cur'] < this['count']; this['cur']++) {
this['tmp'] += '<img src="' + this['postimages'][this['cur']].trim() + '" alt="Image ' + this['cur'] + '" class="postimgelm" />';
this['tmp2'] += '<img src="' + this['postimages'][this['cur']].trim() + '" alt="Image ' + this['cur'] + '" />';
}
$(this).css({
'width': this['tmp'],
'height': this['tmp2']
});
$(this).html(this['tmp'].trim());
preloader.html(this['tmp2']);
var width = 0,
height = 0;
preloader.find('img').each(function () {
if (width < parseInt($(this).width())) {
width = parseInt($(this).width());
}
if (height < parseInt($(this).height())) {
height = parseInt($(this).height());
}
});
console.log('Width: ' + width + ' Height: ' + height);
$(this).css({
'width': width,
'height': height
});
var images = $(this).find('img');
this['cur'] = 0;
images.not(':first').hide();
images.first().css({
'marginTop': '-' + parseInt(images.first().height()),
'marginLeft': '-' + parseInt(images.first().width())
});
var imgcur = 0,
count = this['count'];
this.imgrotate = setInterval(imgrotator, 5000);
function imgrotator() {
console.log(parseInt(images.eq(imgcur).height()));
images.eq(imgcur).css({
'marginTop': '-' + parseInt(images.eq(imgcur).height()),
'marginLeft': '-' + parseInt(images.eq(imgcur).width())
});
console.log(images.eq(imgcur));
images.eq(imgcur).fadeOut(300, function () {
imgcur += 1;
if (imgcur === count) {
imgcur = 0;
}
images.eq(imgcur).fadeIn('slow');
});
}
});
#loading-images {
position:absolute;
top:0;
left:-9999px;
}
.postimgrotator {
position: relative;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
text-align: center;
margin: 10px;
}
.postimgrotator img {
position: absolute;
top: 50%;
left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postimgrotator">http://i1291.photobucket.com/albums/b551/ToxicBKFX/Abstractweek2_zps25dbb861.png http://s28.postimg.org/xkim4q9xp/Aliens_Movie.png http://i.imgur.com/l2SQ4qW.png</div>
<div class="postimgrotator">http://i1291.photobucket.com/albums/b551/ToxicBKFX/Abstractweek2_zps25dbb861.png http://s28.postimg.org/xkim4q9xp/Aliens_Movie.png http://i.imgur.com/l2SQ4qW.png</div>
<div id="loading-images"></div>
Does this help?
var postimgrotator = $('.postimgrotator'),
preloader = $('#loading-images');
postimgrotator.each(function () {
this['tmp'] = '';
this.tmp2 = '';
this.postimages = new Array();
this.cur = 0;
this.count = 0;
console.log($(this));
this['postimages'] = $(this).html().trim().split(" ");
this['count'] = this['postimages'].length;
$(this).html("");
for (this['cur'] = 0; this['cur'] < this['count']; this['cur']++) {
this['tmp'] += '<img src="' + this['postimages'][this['cur']].trim() + '" alt="Image ' + this['cur'] + '" class="postimgelm" />';
this['tmp2'] += '<img src="' + this['postimages'][this['cur']].trim() + '" alt="Image ' + this['cur'] + '" />';
}
$(this).css({
'width': this['tmp'],
'height': this['tmp2']
});
$(this).html(this['tmp'].trim());
preloader.html(this['tmp2']);
var width = 0,
height = 0;
preloader.find('img').each(function () {
if (width < parseInt($(this).width())) {
width = parseInt($(this).width());
}
if (height < parseInt($(this).height())) {
height = parseInt($(this).height());
}
});
console.log('Width: ' + width + ' Height: ' + height);
$(this).css({
'width': width,
'height': height
});
var images = $(this).find('img');
this['cur'] = 0;
images.not(':first').hide();
images.first().css({
'marginTop': '-' + parseInt(images.first().height()),
'marginLeft': '-' + parseInt(images.first().width())
});
var imgcur = 0,
count = this['count'];
this.imgrotate = setInterval(imgrotator, 5000);
function imgrotator() {
console.log(parseInt(images.eq(imgcur).height()));
images.eq(imgcur).css({
'marginTop': '-' + parseInt(images.eq(imgcur).height()),
'marginLeft': '-' + parseInt(images.eq(imgcur).width())
});
console.log(images.eq(imgcur));
images.eq(imgcur).fadeOut(300, function () {
imgcur += 1;
if (imgcur === count) {
imgcur = 0;
}
images.eq(imgcur).fadeIn('slow');
});
}
});
#loading-images {
position:absolute;
top:0;
left:-9999px;
}
.postimgrotator {
position: relative;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
text-align: center;
margin: 10px;
}
.postimgrotator img {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%); /* this */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postimgrotator">http://i1291.photobucket.com/albums/b551/ToxicBKFX/Abstractweek2_zps25dbb861.png http://s28.postimg.org/xkim4q9xp/Aliens_Movie.png http://i.imgur.com/l2SQ4qW.png</div>
<div class="postimgrotator">http://i1291.photobucket.com/albums/b551/ToxicBKFX/Abstractweek2_zps25dbb861.png http://s28.postimg.org/xkim4q9xp/Aliens_Movie.png http://i.imgur.com/l2SQ4qW.png</div>
<div id="loading-images"></div>

Snow until the end of the page

I have a script of snow for the site, I took it from this site. As you can see, the snow does not go the bottom of the page. How can I make it go to the bottom?
Source code:
var SNOW_Time;
var SNOW_dx, SNOW_xp, SNOW_yp;
var SNOW_am, SNOW_stx, SNOW_sty;
var i, SNOW_Browser_Width = $(document).width(), SNOW_Browser_Height = $(document).height();
SNOW_dx = new Array();
SNOW_xp = new Array();
SNOW_yp = new Array();
SNOW_am = new Array();
SNOW_stx = new Array();
SNOW_sty = new Array();
for (i = 0; i < SNOW_no; ++i) {
SNOW_dx[i] = 0;
SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - 50);
SNOW_yp[i] = Math.random() * SNOW_Browser_Height;
SNOW_am[i] = Math.random() * 20;
SNOW_stx[i] = 0.02 + Math.random() / 10;
SNOW_sty[i] = 0.7 + Math.random();
if (i == 0) document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
else document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
}
function SNOW_Weather() {
for (i = 0; i < SNOW_no; ++i) {
SNOW_yp[i] += SNOW_sty[i];
if (SNOW_yp[i] > SNOW_Browser_Height) {
SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - SNOW_am[i] - 30);
SNOW_yp[i] = 0;
SNOW_stx[i] = 0.02 + Math.random() / 10;
SNOW_sty[i] = 0.7 + Math.random();
}
SNOW_dx[i] += SNOW_stx[i];
document.getElementById("SNOW_flake" + i).style.top = SNOW_yp[i] + "px";
document.getElementById("SNOW_flake" + i).style.left = SNOW_xp[i] + SNOW_am[i] * Math.sin(SNOW_dx[i]) + "px";
}
SNOW_Time = setTimeout("SNOW_Weather()", 10);
}
SNOW_Weather();
It looks like it's determined by the variable SNOW_Browser_Height. $(document).height() doesn't return the proper height. You could use this instead:
document.body.getClientRects()[0].height

Categories

Resources