Jquery click to scroll for a specific distance - javascript

I have a horizontal list of images in a div. Each image has a width of 60%. I want to display them like this, at a time only 3 images should be visible the first section should only contain 20% of the image, second should contain 60% (Complete) and third should contain 20% of the image. Problem arises when i want to implement this for a large list of images.
So lets say i have 5 images, i want them to be like this first image to be 20%, second to be 60 % and third to be 20%. When the next button is clicked i want the second image to become 20% , 3rd image 60%(Complete) and 4th image to be 20% width and so on.
This is the code that i have come up with
<div class="center" id="content">
<!--First Image 20%by default--><div id="internal-cover" class="internal" style="width:20%"></div>
<!--Second Image--><div id="internal" class="internal"></div>
<!--Third Image--><div id="internal" class="internal"></div>
<!--fourth Image--><div id="internal" class="internal"></div>
<!--Fifth Image--><div id="internal" class="internal" ></div>
</div>
<style type="text/css">
body
{
margin: 0px auto;
height: 100%;
width: 100%;
overflow: hidden;
}
/* Put your css in here */
.internal{
width: 60%;
height: 100%;
background-size:cover;
display: inline-block;
}
.center{
float: left;
width: 100%;
height: 100vh;
overflow: hidden;
/*will change this to hidden later to deny scolling to user*/
white-space: nowrap;
}
</style>
</body>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Add your javascript here
var first =0;
var second = first+1;
var third= second+1;
var ctr=0;
$('#internal-cover').addClass("left-button");
$(document).on("click",".right-button",function(){
event.preventDefault();
//resetSize();
$('#content').animate({
scrollLeft: "+=812px"//20%Left 60-40% = 60%of Width
}, "fast");
console.log(
$('.center').scrollLeft()
);
first++;
second++;
third++;handleSet();
});
$(document).on("click",".left-button",function(){
event.preventDefault();
//resetSize();
$('#content').animate({
scrollLeft: "-=812px"
}, "fast");
first--;
second--;
third--;
handleSet();
});
function resetSize()
{
$('.internal').each(function(){
$(this).css("width","60%");
});
}
function handleSet()
{
console.log(first+"---"+second+"---"+third);
$('.internal').each(function(){
$(this).removeClass("left-button");
$(this).removeClass("right-button");
});
$('.internal'+first).addClass("left-button")
$('.internal'+third).addClass("right-button");
}
</script>
Something like this

For anyone in future seeking a solution to this. Please have a look at this page https://gist.github.com/tim-reynolds/3019761
var out = $('.center'); //Outer Div containing all the child elements
var tar = $('#internal-target')); //Identifier of the target element, theone
that needs to be centered.
var x = out.width();
var y = tar.outerWidth(true);
var z = tar.index();
var q = 0;
var m = out.find('.internal');
//Just need to add up the width of all the elements before our target.
for(var i = 0; i < z; i++){
q+= $(m[i]).outerWidth(true);
} out.animate({
scrollLeft: Math.max(0, q - (x - y)/2)+"px"
}, "fast");

Related

On Hover Link move Div Horizontally to current hovered Link position

I have a menu with 5 links, Each individual link has the same class and ID "navbarLink"
And I also have another div (which is a skewed shape) "#hoveredLink" that moves from 0 to the actual hovered link position (in the background) I want this shape to take the full width of the hovered link (since they're different on width since each one has more or less text). So My intention is to move this "#hoveredLink" horizontally to reach the position of the "navbarLink" actually hovered.
Haven't succeed yet!
window.onload = function() {
var bsDiv = document.getElementById("hoveredLink");
var x;
$("navbarLink").hover(function() {
x = document.getElementById("hoveredLink").left;
bsDiv.style.left = x + "px";
});
}
Can someone tell me what I'm doing wrong here?
Thanks!
It is this?
If it is not, put an example html.
var menu = document.getElementById("menu");
var up = document.getElementById("up");
menu.onmouseover = function(e){
if(e.target.nodeName != "SPAN"){ return; } // If everything is DIV, you can choose another condition to separate the children from the father.
up.style.left = e.target.offsetLeft - 10 + "px";
up.style.width = e.target.offsetWidth + 20 + "px";
};
menu.onmouseleave= function(e){ // Being the event in the parent is not lost between son and son
up.style.width = 0 + "px";
up.style.left = 0 + "px";
};
.content{
position: relative;
}
#up{
position: absolute;
top: 0px;
left: 0px;
width: 0px;
height: 3px;
background-color: red;
transition: all 0.25s;
}
#menu > span{
margin: 10px;
}
<div class="content">
<div id="up"></div>
<div id="menu">
<span>Link 1</span>
<span>Link_Link 2</span>
<span>Link3</span>
<span>Link 4...</span>
<span>L5</span>
</div>
</div>

Random background image for a webpage

I am trying to find a way that I can have an image that takes up the whole browser window and is responsive. Every time the page is loaded I would like the background image to change from a select group of photos that I have locally.
I have tried a few solutions on here but nothing is really working. The HTML I have is:
<div id="container">
<img src="Images/IMG_3764.JPG" alt="An island in the middle of the sea in Turkey" id="backgroundImage">
</div>
The CSS I have is:
body {
margin: 0;
}
#container {
width: 100%;
height: 100%;
margin: 0;
}
#backgroundImage {
width: 100%;
position: fixed;
top: 0;
left: 0;
}
html, body {
overflow: none !important;
overflow-x: none !important;
overflow-y: none !important;
}
One of the JS solutions that I have tried is this:
var image = new Array ();
image[0] = "http://placehold.it/20";
image[1] = "http://placehold.it/30";
image[2] = "http://placehold.it/40";
image[3] = "http://placehold.it/50";
var size = image.length
var x = Math.floor(size*Math.random())
$('#backgroundImage').attr('src',image[x]);
Your going to need to have an array of images stored in JavaScript like so:
var picArr = [imageSrc1 ,imageSrc2 ,imageSrc3];
After which you'll need some kind of random number that conforms to the amount of image src's you have in the above array.
http://www.w3schools.com/jsref/jsref_random.asp
You'll be using Math.random() here
Then you'll need to create a function that shall be executed when the document loads that changes the src of your background above.
Your final function might look like this:
var picArr = ['src0', 'src1', 'src2', 'src3', 'src4', 'src5', 'src6', 'src7', 'src8', 'src9', ];
var myNumber = Math.floor((Math.random() * 10) + 1);
$(document).ready(function () {
$("#backgroundImage").attr('src', picArr[myNumber]);
});
With jquery you could do something like this
See jsfiddle here.
var images = ['http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg', 'http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg', 'https://s-media-cache-ak0.pinimg.com/originals/c6/8a/51/c68a5157020c8555ca781839d754a1a0.jpg'];
var randomImage = Math.floor(Math.random() * 3)
$(document).ready(function() {
$("#container").css("background-image", "url('" + images[randomImage] + "')");
})
html, body {
height: 100%;
}
#container {
background-repeat: no-repeat;
background-size: cover;
background-position: center;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="container"></div>
</body>

How do you create 3 adjustable divs?

What I want:
| A | | B | | C |
^ ^
When you move the handles left and right A, B, and C resize accordingly
| A | | B | | C |
What I have is the || between B and C sliding, but not resizing B and all I get on the other one is the resize cursor. Basically C is a curtain and covers A and B. I did get min size working for C.
| A | C |
I broke somebody else's perfectly good code to get this far:
var isResizing = false,
who='',
lastDownX = 0;
$(function () {
var container = $('#container'),
left = $('#left'),
right = $('#right'),
middle = $('#middle'),
hand2 = $('#hand2'),
handle = $('#handle');
handle.on('mousedown', function (e) {
isResizing = true;
who=e.target.id;
lastDownX = e.clientX;
});
$(document).on('mousemove', function (e) {
var temp, min;
// we don't want to do anything if we aren't resizing.
if (!isResizing)
return;
min=container.width() * 0.1;
temp = container.width() - (e.clientX - container.offset().left);
if (temp < min)
temp = min;
if (who == 'handle')
right.css('width', temp);
if (who == 'hand2')
left.css('width', temp);
}).on('mouseup', function (e) {
// stop resizing
isResizing = false;
});
});
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 100%;
/* Disable selection so it doesn't get annoying when dragging. */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
}
#container #left {
width: 40%;
height: 100%;
float: left;
background: red;
}
#container #middle {
margin-left: 40%;
height: 100%;
background: green;
}
#container #right {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 200px;
background: rgba(0, 0, 255, 0.90);
}
#container #handle {
position: absolute;
left: -4px;
top: 0;
bottom: 0;
width: 80px;
cursor: w-resize;
}
#container #hand2 {
position: absolute;
left: 39%;
top: 0;
bottom: 0;
width: 80px;
cursor: w-resize;
}
<div id="container">
<!-- Left side -->
<div id="left"> This is the left side's content!</div>
<!-- middle -->
<div id="middle">
<div id="hand2"></div> This is the middle content!
</div>
<!-- Right side -->
<div id="right">
<!-- Actual resize handle -->
<div id="handle"></div> This is the right side's content!
</div>
</div>
Been playing with it here: https://jsfiddle.net/ju9zb1he/5/
I was looking for a solution that required less extensive CSS. It does have one minor bug(FIXED), but hopefully this should get you started. Here is a DEMO.
Also I aimed to use DOM Traversal methods like .next() and .prev() that way it wouldn't be so attribute dependent, and would be easily reusable if you needed a feature like this multiple times on a page.
Edit - Further Explanation
The idea here is onClick of a .handle we want to gather the total width (var tWidth) of the .prev() and .next() divs relative to the .handle in the DOM. We can then use the start mouse position (var sPos) to substract the amount of pixels we've moved our mouse (e.pageX). Doing so gives us the correct width that the .prev() div should have on mousemove. To get the width of the .next() div we need only to subtract the width of the .prev() div from the total width (var tWidth) that we stored onClick of the .handle. Hope this helps! Let me know if you have any further questions, however I will likely be unavailable till tomorrow.
HTML
<div class="container">
<div id="left"></div>
<div id="l-handle" class="handle"></div>
<div id="middle"></div>
<div id="r-handle" class="handle"></div>
<div id="right"></div>
</div>
CSS
#left, #middle, #right {
display: inline-block;
background: #e5e5e5;
min-height: 200px;
margin: 0px;
}
#l-handle, #r-handle {
display: inline-block;
background: #000;
width: 2px;
min-height: 200px;
cursor: col-resize;
margin: 0px;
}
jQuery
var isDragging = false,
cWidth = $('.container').width(),
sPos,
handle,
tWidth;
$('#left, #middle, #right').width((cWidth / 3) - 7); // Set the initial width of content sections
$('.handle').on('mousedown', function(e){
isDragging = true;
sPos = e.pageX;
handle = $(this);
tWidth = handle.prev().width() + handle.next().width();
});
$(window).on('mouseup', function(e){
isDragging = false;
});
$('.container').on('mousemove', function(e){
if(isDragging){ // Added an additional condition here below
var cPos = sPos - e.pageX;
handle.prev().width((tWidth / 2) - cPos); // This was part of the bug...
handle.next().width(tWidth - handle.prev().width());
// Added an update to sPos here below
}
});
Edit
The bug was caused by 2 things.
1) On mousemove we were dividing the total width by two, instead of an updated mouse offset.
2) The sPos was not updating on mousemove, and stayed a static number based off of the click location.
Resolution
Update the sPos on mousemove that way the mouse offset is accurately based off of the previous mousemove position, rather than the click position. When this is done we can then subtract the .next() div's width from the total width. Then we subtract our current mouse position from the remaining width. The fiddle has been updated as well.
$('.container').on('mousemove', function(e){
var cPos = sPos - e.pageX;
if(isDragging && ((tWidth - handle.next().width()) - cPos) <= tWidth){
handle.prev().width((tWidth - handle.next().width()) - cPos);
handle.next().width(tWidth - handle.prev().width());
sPos = e.pageX;
}
});
Edit
Added an additional condition on mousemove to prevent the drag from exceeding the total width (var tWidth).
Can you please explain what you're trying to accomplish?
I don't believe you need to use position: absolute. The premise of absolute positioning is to override the margin and padding imposed on an element by its parent.
You don't need to do this, all elements have relative positioning by default which makes them push eachother around and don't allow overlapping.
I'm probably missing something, but I think this is what you want with nothing but some very basic CSS: http://jsfiddle.net/3bdoazpk/
<div class='first'>
asdf
</div><div class='second'>
dasdf
</div><div class='third'>
sadf
</div>
body {
margin: 0;
}
div {
display: inline-block;
height: 100%;
}
.first, .third {
width: 40%;
}
.first {
background-color: red;
}
.second {
background-color: blue;
width: 20%;
}
.third {
background-color: green;
}

How make a fade slideshow loop?

I am using javascript to change my css class background image every few seconds. It is working great the problem is it just stops after it shows the last image. Can anyone show me what to add to this code so that it will continuously loop itself?
$(window).load(function() {
$(document).ready(function() {
setInterval(fadeDivs, 5000); //call it every 2 seconds
function fadeDivs() {
var visibleDiv = $('.bckgnd:visible:first'); //find first visible div
visibleDiv.fadeOut(400, function() { //fade out first visible div
var allDivs = visibleDiv.parent().children(); //all divs to fade out / in
var nextDivIndex = (allDivs.index(visibleDiv) + 1) % allDivs.length; //index of next div that comes after visible div
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
var lastDiv = $('.backgnd3');
var firstDiv = $('.backgnd1');
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
});
};
});
});
.backgnd1 {
width: 100%;
height: 452px;
background: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/backgnd1.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd2 {
width: 100%;
height: 452px;
background-image: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/the_lodge.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd3 {
width: 100%;
height: 452px;
background-image: url('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/getting_here.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.index_roof_background {
background-color: #000;
width: 1600px;
height: 452px;
margin: 0px;
padding-top: 0px;
margin-left: auto;
margin-right: auto;
}
<div class="index_roof_background">
<div style="position:absolute; z-index: 2;display:block; background-color:#000;" class="bckgnd backgnd1"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd2"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd3"></div>
</div>
A better approach:
You don't need all those backgnd2 classes since you have only those DIVs inside a common parent.
Don't use inline styles! Use your stylesheet.
Don't use fixed width (px). Use % for responsive design.
2000*1331px images are
not suited for the web. Specially not for mobile devices. Care about
your user's bandwidth. When setting a background-image to cover you
don't need to worry about it being repeated.
Make your JS more flexible to element's indexes, count your elements using length.
Create a "current index counter", iterate over it increment it and
resetting using % (reminder).
For a better UX, allow the user to pause on hover.
Here's an eample:
jQuery(function($) { // DOM ready. $ alias in scope.
$('.gallery').each(function() {
var $gal = $(this),
$sli = $gal.find(">*"),
tot = $sli.length,
c = 0,
itv = null;
$sli.hide().eq(c).show(); // Hide all but first slide
function anim() {
c = ++c % tot; // increment/reset counter
$sli.fadeOut().eq(c).stop().fadeIn();
}
function play() {
itv = setInterval(anim, 3000);
}
function pause() {
clearInterval(itv);
}
$gal.hover(pause, play); // Pause on hover
play(); // Start loop
});
});
.gallery {
position: relative;
height: 200px;
}
.gallery>* {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: none 50%;
background-size: cover;
}
<div class="gallery">
<div style="background-image:url(http://placehold.it/800x600/0bf?text=1)"></div>
<div style="background-image:url(http://placehold.it/800x600/f0b?text=2)"></div>
<div style="background-image:url(http://placehold.it/800x600/0fb?text=3)"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First put the firstDiv, lastDiv in their own variables.
Then you will need something like this
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
Tell me if you need more help.
You need to use 2 timeouts to make it loop. A timeout only fires once. The FadeOutDivs function counts down, each time setting a timeout to call itself. Then at zero it fades sets a timeout the call fadeInDivs which start the whole cycle over.
I've got this running on codepen.
$(document).ready(function () {
var interval = 2000;
var fadeDuration = 400;
var allImages = $('.bckgnd');
var count = allImages.length - 1;
var imageCount = allImages.length;
setTimeout(fadeOutDivs, interval);
function fadeOutDivs() {
allImages.eq(count).fadeOut(fadeDuration);
console.log(count);
if (count > 1) {
count--;
setTimeout(fadeOutDivs, interval);
} else {
count = allImages.length - 1;
setTimeout(fadeInDivs, interval)
}
}
function fadeInDivs() {
allImages.fadeIn(fadeDuration);
setTimeout(fadeOutDivs, interval);
}
});

How to grab the width attribute of an element using jQuery?

I created a graph using html, now I want to give it a nice effect when it initially loads. I want the bars of the graph to fly in from the left. The code below does that, only problem is each bar ends up with 70% width (obviously since I set that in the jQuery code). Instead I need that number to be unique to the width set within the bars (span tags). I assume the answer would be something like:
$(this).attr('width')...
but I can't get it to work, please help.
The Code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<style type="text/css">
div.graph { display: none; border: 1px solid red; height: 200px; width: 400px; margin: 0 auto; }
div.graph span { display: none; display: block; background: red; height: 20px; margin-bottom: 10px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$('div.graph').fadeIn('slow');
$('div.graph > span').animate({
width: "70%"
}, 1500 );
});
</script>
<div class="graph">
<span style='width:10%'></span>
<span style='width:40%'></span>
<span style='width:25%'></span>
<span style='width:15%'></span>
<span style='width:10%'></span>
</div><!-- graph -->
edit
After reading your code, if you don't care for non-JS support [there are many casex when you don't], you can use .data() method [very elegant, too :)]
HTML:
<span data-width="10%">Hello</span>
JS:
$('div.graph > span').each(function(){
$(this).animate({
width: $(this).data('width')
}, 1500 );
});
updated example
http://jsfiddle.net/vGUM7/2/
code
.animate({
'width': $(element).width()
},500);
example
http://jsfiddle.net/vGUM7/1/
[updated with %]
Try this on for size:
$('div.graph > span').each(function(){
var w=$(this).width();
$(this).width(0);
$(this).animate({
width: w
}, 1500 );
});
you could do something like:
$(document).ready(function() {
$('div.graph > span').each(function() {
var $this = $(this);
var w = $this.width(); // Grab what it should be
$this.width(0); // Reset so it does the animation
$this.animate({
width: w
}, 1500 );
});
$('div.graph').fadeIn('slow');
});
It reads what you want the bar to be, then sets it back to 0. setting up the animation to go. After its all set, the fade in starts
Try this...
$('div.graph').fadeIn('slow');
var bars = $('div.graph > span');
for(var i=0; i<bars.length; i++){
var w = $(bars[i]).width();
$(bars[i]).width(0);
$(bars[i]).animate({
width: w
}, 1500);
}
$(this).width() should work, or else $(this).css('width');
however .css('width') will return the value that the css has, so could be '10%' for example or 'auto'

Categories

Resources