$(window).load() is executing 2 times? - javascript

I am using $(window).load() to change some image sizes for a thumbnail gallery and then configuring a slideshow based on image sizes after that. For some reason, the code is executing 2 times. I can tell this because in my configuration funcition I am using jQuery to wrap a div around another div. However, when I look at my HTML when the page loads, there are 2 instances of the same div being wrapped.
I used the javascript debugger to look at whats happening and my code executes and then goes into the jquery-min.js, then goes back to my function as if it were called a second time. Here is my code:
HTML
<?php session_start(); include ('dbConfig.php'); include('main.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Main Gallery</title>
<link rel="stylesheet" href="css/reset.css" type="text/css" />
<link rel="stylesheet" href="css/style.css" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Great+Vibes' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<!--[if IE]>
<style type="text/css">
.transblack {
background:transparent;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#50000000,endColorstr=#50000000);
zoom: 1;
}
.transwhite {
background:transparent;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#50FFFFFF,endColorstr=#50FFFFFF);
zoom: 1;
}
</style>
<![endif]-->
<script>
$(window).load(function(){
$('#gallery ul li').each(function() {
var $frame = $(this).children('div');
$frame.children('img').superFit();
});
$('#gallery').css('visibility', 'visible');
configGallery();
});
$(document).ready(function(){
$('#filter').hide();
$('#photoWrap').hide();
$('#gallery').css('visibility', 'hidden');
});
</script>
</head>
<body>
<div id="mainWrap">
<?php include('adminPanel.php'); ?>
<div id="photoWrap">
<div id="controlLeft" class="control"></div>
<div id="slideShow">
<div id="slideContainer">
<?php
if(isset($_GET['c']) && isset($_GET['p']))
{
if(isAuthentic($_GET['c'], $_GET['p']))
{
getSlideshow($_GET['c']);
}else{
getSlideshow();
}
}else{
getSlideshow();
}
?>
</div>
</div>
<div id="controlRight" class="control"></div>
</div>
<div id="container">
<div id="filter" class="transblack"></div>
<div id="titleWrap"></div>
<div id="navWrap">
<div id="nav">
<ul>
<li>Home</li>
<li>Gallery</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="clientHolder">
<span id="clientSelector">Select Gallery: <select onchange="getGallery(document.getElementById('clientSelect').value)" id="clientSelect">
<option value="-2">--Select--</option>
<option value="-1">Public Gallery</option>
<?php
if(isset($_GET['c']) && isset($_GET['p']))
{
if(isAuthentic($_GET['c'], $_GET['p']))
{
getClients($_GET['c']);
}else{
getClients();
}
}else{
getClients();
}
?>
</select></span>
</div>
<div id="gallery">
<ul>
<?php
if(isset($_GET['c']) && isset($_GET['p']))
{
if(isAuthentic($_GET['c'], $_GET['p']))
{
getMain($_GET['c']);
}else{
echo "<h2>The password you entered was incorrect</h2>";
}
}else{
getMain();
}?>
</ul>
</div>
</div>
</div>
<script src="js/md5.js" type="text/javascript"></script>
<script src="js/helper.js" type="text/javascript"></script>
<script src="js/superFit.js" type="text/javascript"></script>
</body>
</html>
Javascript
This first one is my jQuery plugin I created
(function($) {
$.fn.superFit = function(options) {
var $this = $(this);
var parent = $this.parent();
var parentW = parent.width();
var parentH = parent.height();
var imgW = $this.width();
var imgH = $this.height();
var imgRatio = imgH / imgW;
var parentRatio = parentH / parentW;
if(imgRatio < parentRatio) //We have a landscape image
{
//First set the height of image to be 100%;
$this.css('height', '100%');
imgW = $this.width();
parentW = parent.width();
//Now center the image
$this.css('margin-left', -(imgW/2)+(parentW/2));
}else{ //We have a portrait image
$this.css('width', '100%');
}
}
})(jQuery);
And this is the function that is called twice
function configGallery()
{
var currentPosition;
var slides = $('.slide');
var currentSlide;
var currentImg;
var slideWidth = 720;
var numberOfSlides = slides.length;
var imgRatio;
var slideRatio = $('#slideShow').height() / slideWidth;
slides.wrapAll('<div id="slideInner"></div>');
$('.imgHolder').click(function(){
$('#filter').show();
$('#photoWrap').show();
currentPosition = $('.imgHolder').index(this);
$('#slideShow').width(slideWidth);
// Remove scrollbar in JS
$('#slideContainer').css('overflow', 'hidden');
//Change image size based on resolution
// Wrap all .slides with #slideInner div
slides.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', (slideWidth * numberOfSlides));
// Hide left arrow control on first load
manageControls(currentPosition);
$('#slideInner').css('margin-left' , slideWidth*(-currentPosition));
$('#photoWrap').css('margin-top', (screen.height/3)-($('#photoWrap').height()/3));
changeSize();
});
// Create event listeners for .controls clicks
$('.control')
.bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='controlRight') ? currentPosition+1 : currentPosition-1;
manageControls(currentPosition);
changeSize();
$('#slideShow').width(slideWidth);
$('#slideInner').css('margin-left', slideWidth*(-currentPosition));
});
$('#filter').click(function(){
$(this).hide();
$('#photoWrap').hide();
});
// manageControls: Hides and shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==-1){ currentPosition = numberOfSlides-1; }
else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides){ currentPosition = 0; }
else{ $('#rightControl').show() }
}
function changeSize(){
currentSlide = $('.slide').get(currentPosition);
currentImg = $(currentSlide).children('img').first();
imgRatio = $(currentImg).height() / $(currentImg).width();
if(imgRatio < slideRatio)
{
$(currentImg).addClass('landscape');
//Vertically align
var thisHeight = $(currentImg).height();
$(currentImg).css('margin-top', ($('#slideShow').height()/2)-(thisHeight/2));
}else{
$(currentImg).addClass('portrait');
}
}
}

Why are you using $(window).load()? I'm asking if there's a specific reason or not.
The standard jQuery way uses DOMReady via:
$(document).ready()
Or:
$(function(){
});

var once = false;
function configGallery() {
if ( ! once) {
once = true;
// Rest of the function
}
}
That would make it only execute once.

Related

Is there a solution for a font size slider affecting body tag but just need it to affect some css classes

I have the following code to change the body font size on a web site. Its working fine but the resizing gets awful as it affects every text into de body. So I have tried to transform it to only apply the font resizing just to some css classes but I can not find the solution. What I would like to do is that the resizing just affect, for example, .content-block, .main-content, .etc,....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1"/>
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function (e) {
var newSize = this.value,
defaultSize = body.style.getPropertyValue('font-size'),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>
You can use css variable in needed classes and in javascript simply change value of that variable:
var curSize = null; // localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
var defaultSize = body.style.getPropertyValue('font-size');
if (curSize) {
var saveSize = curSize;
document.documentElement.style.setProperty("--font-size", saveSize + "px");
//body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function(e) {
var newSize = this.value,
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
document.documentElement.style.setProperty("--font-size", newSize + "px");
// body.style.fontSize = newSize + 'px';
// localStorage.setItem("saveSize", newSize);
}
});
:root {
--font-size: 1em;
}
.affected,
.dynamic {
font-size: var(--font-size);
}
/* ignore this */
.affected:before,
.dynamic:before,
.content :not(.affected):not(.dynamic):before {
content: "dynamic font size:";
background-color: lightgreen;
border: 1px solid grey;
font-size: initial;
margin: 1em;
padding: 0.2em;
}
.content :not(.affected):not(.dynamic):before {
content: "static font size:";
background-color: pink;
}
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
<div class="content">
<h1>Changing Font Size</h2>
<p class="dynamic">I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
</div>
The Vanowm answer is ok and works very well but I need the localStorage to store the selected font size to persist over sessions, so I am going to post an answer with that enabled just in case someone else could need a similar approach.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1"/>
</div>
<div>
<h1>Changing Font Size</h2>
<p class="dynamic">I am just a boring text, existing here solely for the purpose of this demo</p>
<p class="affected">And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
var defaultSize = body.style.getPropertyValue('font-size');
if (curSize) {
var saveSize = curSize;
document.documentElement.style.setProperty("--font-size", saveSize + "px");
// body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function(e) {
var newSize = this.value,
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
document.documentElement.style.setProperty("--font-size", newSize + "px");
// body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>

How to detect correct div data attribute when each hitting the top of the page

I am working on the below code. Why am I not able to detect which div is reaching at the top of page in both down or up scroll?
$(window).scroll(function() {
$(".container").each(function() {
var $that = $(this);
var po = $(this).offset().top;
if (po >= 0 && po <= 300) {
console.log($that.data('map'));
}
});
});
.container {
height: 690px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Tow</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>
You'll need to use $(window).scrollTop(); as well as $that.outerHeight()
$(window).scroll(function() {
var windowScrollTop = $(this).scrollTop(); // window scroll top
$(".container").each(function() {
var $that = $(this);
var po = $that.offset().top;
var poHeight = $that.outerHeight(true); // the height of the element
var distanceTop = 100; // the distance from top to run the action .. it can be 0 if you want to run the action when the element hit the 0 top
if (windowScrollTop + distanceTop >= po && windowScrollTop + distanceTop <= po + poHeight) {
if(!$that.hasClass('red')){ // if element dosen't has class red
console.log($that.data('map'));
$(".container").not($that).removeClass('red'); // remove red class from all
$that.addClass('red'); // add red class to $that
}
}
});
}).scroll(); // run the scroll onload
.container {
height: 690px;
}
.container.red{
background : red;
color : #fff;
font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Two</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

JQuery Remove not removing specified div

I have a small page on which you can add squares of different colors to a div with a button. After adding them, you can remove them by double clicking any of the squares created.
My code works well, when adding elements. However when I want to remove a square, I just get to remove one and after that I can´t make the element disappear on HTML even though the counter does decrease. I´m a doing something wrong with the remove() function? Right now I´m just focusing on the blue (Azul) color.
Here´s my code
https://jsfiddle.net/kdwyw0mc/
var azules = 0;
var rojos = 0;
var amarillos = 0;
var verdes = 0;
function eliminar(cuadro){
azules = parseInt(jQuery('#num-azules').text());
verdes = parseInt(jQuery('#num-verdes').text());
rojos = parseInt(jQuery('#num-rojos').text());
amarillos = parseInt(jQuery('#num-amarillos').text());
if(cuadro[0].classList[1]=='blue'){
azules = azules -1;
}
else if(cuadro[0].classList[1]=='red'){
rojos--;
}
else if(cuadro[0].classList[1]=='yellos'){
amarillos--;
}
else if(cuadro[0].classList[1]=='green'){
verdes--;
}
cuadro.remove();
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
function agregar(){
jQuery('span#num-azules').val(azules);
var numCuadros = jQuery("#numero").val();
var color = $('#color option:selected').text();
for( i = 0; i< numCuadros; i++){
if(color=='Azul'){
/*jQuery(".square").append(function(){
return jQuery('<div class="square blue"> </div>').ondblclick(eliminar);
})*/
var newSquare = jQuery('<div class="square blue"> </div>')
var a = jQuery(".squares").append(newSquare);
newSquare.dblclick(function(){eliminar(newSquare);})
azules += 1;
}
else if(color=='Rojo'){
jQuery(".squares").append('<div class="square red"> </div>')
rojos+= 1;
}
else if(color=='Amarillo'){
jQuery(".squares").append('<div class="square yellow"> </div>')
amarillos+= 1;
}
else if(color=='Verde'){
jQuery(".squares").append('<div class="square green"> </div>')
verdes+= 1;
}
}
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
/*
* jQuery("#agregar").click(function(){
agregar();
});
VS
jQuery("#agregar").click(agregar());
* */
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
jQuery("#agregar").click(function(){
agregar();
});
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles/reset.css"/>
<link rel="stylesheet" href="styles/main.css"/>
</head>
<body>
<div class="main-content">
<div class="toolbar">
Numero Cuadrados: <input id="numero"type="text"/>
<select id="color" name="color">
<option value="azul">Azul</option>
<option value="rojo">Rojo</option>
<option value="amarillo">Amarillo</option>
<option value="verde">Verde</option>
</select>
<button id="agregar">Agregar</button>
</div>
<div class="squares">
</div>
<div class="numeros">
<p>Azules: <span id="num-azules">0</span> </p>
<p>Rojos: <span id="num-rojos">0</span></p>
<p>Verde: <span id="num-verdes">0</span></p>
<p>Amarillo: <span id="num-amarillos">0</span></p>
</div>
</div>
<script src="scripts/jquery-1.11.3.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
This is an inefficient way of registering / listening to events, it is better to delegate the event handling to a wrapper (parent) container:
$("#container").on("dblclick", ".square", function(){
$(this).remove();
)};
on works for dynamically created elements; since the container was already in the DOM, it can continue listening to events coming from any other, newly created child element that has class .square.
http://api.jquery.com/on/
Edit:
One way of solving the counter problem would be to do something like this:
var StateObj = function(){
this.counter = 0;
this.arrSquares = [];
this.increaseCounter = function(){
this.counter += 1;
},
this.decreaseCounter = function(){
this.counter -= 1;
},
this.addSquare = function(id, color){
this.arrSquares.push({id: id, color: color});
},
this.getSquareById = function(id){
return square = $.grep(this.arrSquares, function(){ return id == id; });
}
}
var stateObj = newStateObj();
$("#container").on("dblclick", ".square", function(e){
$(this).remove();
var id = $(e.currentTarget).attr("id");
stateObj.increaseCounter();
console.log(stateObj.counter);
)};

How to set total height on Jinvert Scroll

I've created a horizontal scrolling website with parallax using Jquery Plugin called Jinvertscroll. However, the scrolling stops before reaching the end of the page. Demo at https://dl.dropboxusercontent.com/u/246684898/VipSitaraman.com/examples/index.htm. Please tell me how to change the total scroll length on the plug in.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vip Sitaraman</title>
<link rel="stylesheet" href="css/example.css" />
<body style="background-color:#383938">
<div id="main">
<div class="suit scroll">
<img id="animation" src="images/1.png" alt="" />
</div>
<div class="plane scroll">
<img class="plane" src="images/plane.png" alt="" />
</div>
<div class="pinned scroll">
<a id="navv">< </a><a id="nav"> ></a>
</div>
<div class="bg scroll">
<img src="images/bg.jpg" alt="" />
</div>
<div class="horizon scroll">
<img src="images/horizon_01.png" alt="" />
</div>
<div class="middle scroll">
<img src="images/middle_01.png" alt="" />
</div>
<div class="front scroll">
<img src="images/front_01.png" alt="" />
</div>
<div class="research scroll" id="research">
</div>
<div class="music scroll" id="music">
</div>
</div>
</div>
</div>
<script type="text/javascript" src="../libs/jquery.min.js"></script>
<script type="text/javascript" src="../dist/js/jquery.jInvertScroll.js"></script>
<script type="text/javascript">
(function($) {
$.jInvertScroll(['.scroll'], // an array containing the selector(s) for the elements you want to animate
{
height: 3000, // optional: define the height the user can scroll, otherwise the overall length will be taken as scrollable height
onScroll: function(percent) { //optional: callback function that will be called when the user scrolls down, useful for animating other things on the page
console.log(percent);
}
});
}(jQuery));
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var b = 300
var bodyHeight = $("body").height()-$(window).height();
window.onscroll = function() {
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
};
};
});//]]>
</script>
<script type='text/javascript'>//<![CDATA[
$(function (){
var sdegree = 0;
var orig = 0;
var z = 1 + Math.random() * 20
$(window).scroll(function () {
if (sdegree > -10 && sdegree < 10 && sdegree - orig >= 0) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree > -10 && sdegree < 10 && sdegree - orig < 0) {
orig = sdegree;
sdegree = sdegree - 1;
} else if (sdegree <= -10) {
orig = sdegree;
sdegree = sdegree + 1;
} else if (sdegree >= 10) {
orig = sdegree;
sdegree = sdegree - 1;
} else {
orig = sdegree;
}
var srotate = "rotate(" + sdegree + "deg)";
$('.plane').css('z-index','z');
$(".plane").css({
transform: srotate
});
});
});
//]]>
</script>
<script type="text/javascript">
$(function() {
$("#nav").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()+800
}, 1000);
if($('#animation').attr('src') != 'images/suit.gif'){
$('#animation').attr('src','images/suit.gif');
}
});
});
</script>
<script type="text/javascript">
$(function() {
$("#navv").click(function() {
$('html,body').animate({
scrollTop: $(document).scrollTop()-800
}, 1000);
});
});
</script>
</body>
</html>
If all you need is to define size, here's what you are looking for:
$.jInvertScroll(['.myScrollableElements'], {
width: 'auto', // Page width (auto or int value)
height: 'auto', // Page height (the shorter, the faster the scroll)
onScroll: function(percent) {
// Callback function that will be called each time the user
// scrolls up or down, useful for animating other parts
// on the page depending on how far the user has scrolled down
// values go from 0.0 to 1.0 (with 4 decimals precision)
}
});
SOURCE

Categories

Resources