Fixed position to show on some sections but hidden on home - javascript

I was wondering if someone could give me a solution.
I have a website that scrolls horizontally. I divided it in six sections being the first section the home page. This home page features a navigation system different to the rest of sections for which I used a standard horizontal nav bar.
My problem is that I need the nav bar to stay fixed on its position so when I scroll down, it's still there but I don't want this nav bar to show on the home screen. Is there anyway I can have the nav bar fixed on different sections of the site while is hidden on the homepage?
Any help will be much appreciated. I attach the fiddle: http://jsfiddle.net/zpeua/
Many thanks guys!
Gon
HTML
<div id="wrapper">
<div id="mask">
<div id="item1" class="item">
<div id="Header" class="effect2">
<div id="Logo"></div>
<div id="ContactDetails"></div>
</div>
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item1"></a>
<div class="content"></div>
</div>
<div id="item2" class="item">
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item2"></a>
<div class="content"></div>
</div>
<div id="item3" class="item">
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item3"></a>
<div class="content"></div>
</div>
<div id="item4" class="item">
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item4"></a>
<div class="content"></div>
</div>
<div id="item5" class="item">
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item5"></a>
<div class="content"></div>
</div>
<div id="item6" class="item">
<div id="nav" class="Home">
<ul>
<li>Home
</li>
<li>About
</li>
<li>Events
</li>
<li>Repertoire
</li>
<li>Media
</li>
<li>Contact
</li>
</ul>
</div> <a name="item6"></a>
<div class="content"></div>
</div>
</div>
CSS
body {
height:100%;
width:100%;
margin:0;
padding:0;
overflow:hidden;
text-align:center;
}
#wrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-color: #fff;
overflow: hidden;
}
#Header {
position:fixed;
z-index:10;
width:100%;
text-align:center;
padding:33px 0;
background:#FFF;
-webkit-box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.3);
-moz-box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.3);
box-shadow: 0px 1px 5px 0px rgba(50, 50, 50, 0.3);
overflow:auto;
}
#nav {
width:100%;
position:absolute;
top:127px;
text-align:center;
background:#FFF;
z-index:999;
padding-top:7px;
}
#nav ul {
width:100%;
max-width:1015px;
margin:0 auto;
list-style:none;
display:inline-block;
}
#nav ul li {
float:left;
width:auto;
margin:0 60px 0 60px;
}
#nav li a {
color:#999;
}
#nav li a:hover {
color:#000;
}
#mask {
width:600%;
height:100%;
background-color:#fff;
}
.item {
width:16.6%;
height:100%;
overflow-y:scroll;
float:left;
background-color:#fff;
}
.content {
width:100%;
height:100%;
top:165px;
margin:0 auto;
background-color:#fff;
position:relative;
}
.selected {
background:#fff;
font-weight:700;
}
.clear {
clear:both;
}
JS
$(document).ready(function () {
$('a.panel').click(function () {
$('a.panel').removeClass('selected');
$(this).addClass('selected');
current = $(this);
$('#wrapper').scrollTo($(this).attr('href'), 800);
return false;
});
$(window).resize(function () {
resizePanel();
});
});
function resizePanel() {
width = $(window).width();
height = $(window).height();
mask_width = width * $('.item').length;
$('#debug').html(width + ' ' + height + ' ' + mask_width);
$('#wrapper, .item').css({
width: width,
height: height
});
$('#mask').css({
width: mask_width,
height: height
});
$('#wrapper').scrollTo($('a.selected').attr('href'), 0);
}
;(function( $ ){
var $scrollTo = $.scrollTo = function( target, duration, settings ){
$(window).scrollTo( target, duration, settings );
};
$scrollTo.defaults = {
axis:'xy',
duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
};
// Returns the element that needs to be animated to scroll the window.
// Kept for backwards compatibility (specially for localScroll & serialScroll)
$scrollTo.window = function( scope ){
return $(window)._scrollable();
};
// Hack, hack, hack :)
// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
$.fn._scrollable = function(){
return this.map(function(){
var elem = this,
isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if( !isWin )
return elem;
var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
return $.browser.safari || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
});
};
$.fn.scrollTo = function( target, duration, settings ){
if( typeof duration == 'object' ){
settings = duration;
duration = 0;
}
if( typeof settings == 'function' )
settings = { onAfter:settings };
if( target == 'max' )
target = 9e9;
settings = $.extend( {}, $scrollTo.defaults, settings );
// Speed is still recognized for backwards compatibility
duration = duration || settings.speed || settings.duration;
// Make sure the settings are given right
settings.queue = settings.queue && settings.axis.length > 1;
if( settings.queue )
// Let's keep the overall duration
duration /= 2;
settings.offset = both( settings.offset );
settings.over = both( settings.over );
return this._scrollable().each(function(){
var elem = this,
$elem = $(elem),
targ = target, toff, attr = {},
win = $elem.is('html,body');
switch( typeof targ ){
// A number will pass the regex
case 'number':
case 'string':
if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
targ = both( targ );
// We are done
break;
}
// Relative selector, no break!
targ = $(targ,this);
case 'object':
// DOMElement / jQuery
if( targ.is || targ.style )
// Get the real position of the target
toff = (targ = $(targ)).offset();
}
$.each( settings.axis.split(''), function( i, axis ){
var Pos = axis == 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
old = elem[key],
max = $scrollTo.max(elem, axis);
if( toff ){// jQuery / DOMElement
attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
// If it's a dom element, reduce the margin
if( settings.margin ){
attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
}
attr[key] += settings.offset[pos] || 0;
if( settings.over[pos] )
// Scroll to a fraction of its width/height
attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
}else{
var val = targ[pos];
// Handle percentage values
attr[key] = val.slice && val.slice(-1) == '%' ?
parseFloat(val) / 100 * max
: val;
}
// Number or 'number'
if( /^\d+$/.test(attr[key]) )
// Check the limits
attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );
// Queueing axes
if( !i && settings.queue ){
// Don't waste time animating, if there's no need.
if( old != attr[key] )
// Intermediate animation
animate( settings.onAfterFirst );
// Don't animate this axis again in the next iteration.
delete attr[key];
}
});
animate( settings.onAfter );
function animate( callback ){
$elem.animate( attr, duration, settings.easing, callback && function(){
callback.call(this, target, settings);
});
};
}).end();
};
// Max scrolling position, works on quirks mode
// It only fails (not too badly) on IE, quirks mode.
$scrollTo.max = function( elem, axis ){
var Dim = axis == 'x' ? 'Width' : 'Height',
scroll = 'scroll'+Dim;
if( !$(elem).is('html,body') )
return elem[scroll] - $(elem)[Dim.toLowerCase()]();
var size = 'client' + Dim,
html = elem.ownerDocument.documentElement,
body = elem.ownerDocument.body;
return Math.max( html[scroll], body[scroll] )
- Math.min( html[size] , body[size] );
};
function both( val ){
return typeof val == 'object' ? val : { top:val, left:val };
};
})( jQuery );

You can easily fix the header to the top of the page and use jQuery to detect what page you're on within $(document).ready() and hide the header when you are on the home page. So within your $('a.panel').click() you'll just need this:
if($(this).html() == 'Home' && !$('#HomeNavId').is(':visible'))
{
$('#HomeNavId').show();
} else {
$('#HomeNavId').hide();
}

Related

How to use slider like changer over image to replace with another images

All
I want to make a image "slider" which will uncover the image underneath it when the user grabs the handle and drags it.
http://jsfiddle.net/M8ydk/1/
In this example, the user grabs the handle and moves it on the slider. I would like the same thing, but revealing the image behind it.
<div id="slider">
<ul>
<li style="background-color: #F00"></li>
<li style="background-color: #0F0"></li>
<li style="background-color: #00F"></li>
</ul>
</div>
#slider {
width: 400px;
overflow: hidden;
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
width: 400px;
height: 400px;
float: left;
}
Number.prototype.roundTo = function(nTo) {
nTo = nTo || 10;
return Math.round(this * (1 / nTo) ) * nTo;
}
$(function() {
var slides = $('#slider ul').children().length;
var slideWidth = $('#slider').width();
var min = 0;
var max = -((slides - 1) * slideWidth);
$("#slider ul").width(slides*slideWidth).draggable({
axis: 'x',
drag: function (event, ui) {
if (ui.position.left > min) ui.position.left = min;
if (ui.position.left < max) ui.position.left = max;
},
stop: function( event, ui ) {
$(this).animate({'left': (ui.position.left).roundTo(slideWidth)})
}
});
});
Result image will change like this if we drag from pivot point
By replacing the image in background Both image are come parallel While i want they overlay on each other as display in 2nd picture
Current Results
Desire Results :
Replace
<div id="slider">
<ul>
<li style="background-color: #F00"></li>
<li style="background-color: #0F0"></li>
<li style="background-color: #00F"></li>
</ul>
</div>
with
<div id="slider">
<ul>
<li style="background-image: url('path to image')"></li>
<li style="background-image: url('path to image')"></li>
<li style="background-image: url('path to image')"></li>
</ul>

Carousel slides incorrectly when swiping or when clicking the slider controls (next/prev)

I've just finished building a carousel I've been working on that uses swipe/touch and also uses controls such as prev/next to control the carousel. Right now I'm having an issue regarding about the carousel behavior. Basically I'm trying to make it slide one by one. Here is a sample of the code I've been working on. Right now it seems to be sliding by 2 or 3 depending on how many carousel I've placed.
I'm also having an issue with regards to making it responsive also
function fCarousel() {
// var activeSlide = 0;
// $('.faculty-carousel').attr('data-slide', '0');
var viewPortSize = $(window).width(),
facultyPanel = $('.faculty-carousel .faculty-items li'),
profileCount = facultyPanel.length,
activeSlide = 0,
carousel = $('.faculty-carousel .faculty-items');
$('.faculty-carousel').attr('data-slide', '0');
//Set Panel Size based on viewport
if (viewPortSize <= 1920 ) {
var profilePanelSize = viewPortSize / 5
}
if (viewPortSize < 1024 ) {
var profilePanelSize = viewPortSize / 4
}
if (viewPortSize < 768 ) {
var profilePanelSize = viewPortSize / 3
}
if (viewPortSize < 480 ) {
var profilePanelSize = viewPortSize
}
carousel.outerWidth( profilePanelSize * profileCount );
facultyPanel.outerWidth(profilePanelSize);
carousel.css('transform', 'translateX(' + 0 + '% )');
$('.prev').on('click', function(e) {
event.stopPropagation();
var carouselWrapper = $(this).closest('.faculty-carousel'),
facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
facultyProfileCount = facultyProfilePanel.length,
viewPortSize = $(window).width(),
carousel = carouselWrapper.find('.faculty-items'),
position = 0,
currentSlide = parseInt(carouselWrapper.attr('data-slide'));
// Check if data-slide attribute is greater than 0
if (currentSlide > 0) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
carousel.css('transform', 'translateX(' + transformPercentage + '% )');
// Update data-slide attribute
carouselWrapper.attr('data-slide', currentSlide);
activeSlide = currentSlide;
}
});
$('.next').on('click', function(e) {
event.stopPropagation();
// store variable relevent to clicked slider
var carouselWrapper = $(this).closest('.faculty-carousel'),
facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
facultyProfileCount = facultyProfilePanel.length,
viewPortSize = $(window).width(),
carousel = carouselWrapper.find('.faculty-items'),
position = 0,
currentSlide = parseInt(carouselWrapper.attr('data-slide'));
// Check if dataslide is less than the total slides
if (currentSlide < facultyProfileCount - 1) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
carousel.css('transform', 'translateX(' + transformPercentage + '% )');
// Update data-slide attribute
carouselWrapper.attr('data-slide', currentSlide);
activeSlide = currentSlide;
}
})
$('.faculty-carousel .faculty-items').each(function() {
// create a simple instance
// by default, it only adds horizontal recognizers
var direction;
var touchSlider = this;
var mc = new Hammer.Manager(this),
itemLength = $(this).find('li').length,
count = 0,
slide = $(this),
timer;
var sliderWrapper = slide,
slideItems = sliderWrapper.find('li'),
//slider = sliderWrapper.find('li'),
totalPanels = slideItems.length,
currentSlide = parseInt(sliderWrapper.attr('data-slide'));
// mc.on("panleft panright", function(ev) {
// direction = ev.type;
// });
mc.add(new Hammer.Pan({
threshold: 0,
pointers: 0
}))
mc.on('pan', function(e) {
var percentage = 100 / totalPanels * e.deltaX / window.innerWidth;
var transformPercentage = percentage - 100 / totalPanels * activeSlide;
touchSlider.style.transform = 'translateX( ' + transformPercentage + '% )';
var sliderWrapper = $(e.target).closest('.faculty-carousel')
if (e.isFinal) { // NEW: this only runs on event end
var newSlide = activeSlide;
if (percentage < 0)
newSlide = activeSlide + 1;
else if (percentage > 0)
newSlide = activeSlide - 1;
goToSlide(newSlide, sliderWrapper);
}
});
var goToSlide = function(number, sliderWrapper) {
if (number < 0)
activeSlide = 0;
else if (number > totalPanels - 1)
activeSlide = totalPanels - 1
else
activeSlide = number;
sliderWrapper.attr('data-slide', activeSlide);
touchSlider.classList.add('slide-animation');
var percentage = -(100 / totalPanels) * activeSlide;
touchSlider.style.transform = 'translateX( ' + percentage + '% )';
timer = setTimeout(function() {
touchSlider.classList.remove('slide-animation');
}, 400);
};
});
}
$(document).ready(function() {
fCarousel();
})
$(window).on('resize', function(){
fCarousel();
})
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
.faculty-items li {
height : 100px;
}
.faculty-items li:nth-child(odd) {
background-color : grey;
}
.faculty-items li:nth-child(even) {
background-color : aqua
}
.faculty-items {
overflow : hidden;
position : relative;
right : 0;
display : flex;
-webkit-transition: transform 0.3s linear;
}
.faculty-carousel .controls {
display : block;
}
<!doctype html>
<html>
<head>
<title>Carousel</title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
</head>
<body>
<div class="faculty-carousel">
<ul class="faculty-items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
<div class="controls">
<div class="prev">
prev
</div>
<div class="next">
next
</div>
</div>
</div>
<div class="faculty-carousel">
<ul class="faculty-items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
<div class="controls">
<div class="prev">
prev
</div>
<div class="next">
next
</div>
</div>
</div>
<div class="faculty-carousel">
<ul class="faculty-items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
<div class="controls">
<div class="prev">
prev
</div>
<div class="next">
next
</div>
</div>
</div>
</body>
</html>
Okay, my first answer here was done in a hurry but I believe I have a clear JavaScript representation of what most modern Carousels would function like, although the rest is up to you if you choose to use it.
Here is the JavaScript side of things well explained
// Index all Carousel
for (var i = 0; i < document.getElementsByClassName("carousel").length; i++) {
// Create a container for all the slides
document.getElementsByClassName("carousel")[i].innerHTML = (
'<div class="slides-container">' +
document.getElementsByClassName("carousel")[i].innerHTML +
'</div>'
);
// If the Carousel is automated
if (document.getElementsByClassName("carousel")[i].getAttribute("data-auto")) {
// Remove all white-space in the Carousel's "data-auto" attribute.
document.getElementsByClassName("carousel")[i].setAttribute("data-auto", document.getElementsByClassName("carousel")[i].getAttribute("data-auto").replace(/ /g, ""));
// Set the Carousel direction
document.getElementsByClassName("carousel")[i]._direction = String(document.getElementsByClassName("carousel")[i].getAttribute("data-auto").slice(0, document.getElementsByClassName("carousel")[i].getAttribute("data-auto").indexOf("_")));
// Set the Carousel interval
document.getElementsByClassName("carousel")[i]._interval = (parseFloat(document.getElementsByClassName("carousel")[i].getAttribute("data-auto").slice(document.getElementsByClassName("carousel")[i].getAttribute("data-auto").indexOf("_")).replace("_", "")) * 1000)
};
// Index all Carousel slides
for (var j = 0; j < document.getElementsByClassName("carousel")[i].querySelector(".slides-container").children.length; j++)
// Hide them
document.getElementsByClassName("carousel")[i].querySelector(".slides-container").children[j].hidden = true;
// Show the first one or the specified slide
document.getElementsByClassName("carousel")[i].querySelector(".slides-container").children[(parseInt(document.getElementsByClassName("carousel")[i].getAttribute("data-active")) || 0)].hidden = false;
// Carousel Next
document.getElementsByClassName("carousel")[i]._next = function() {
// Index all Carousel Slides
for (var j = 0; j < this.querySelector(".slides-container").children.length; j++)
// Show the next slide in the set
if (this.querySelector(".slides-container").children[j].hidden == false) {
this.querySelector(".slides-container").children[j].hidden = true;
(this.querySelector(".slides-container").children[j].nextElementSibling || this.querySelector(".slides-container").children[0]).hidden = false;
break
}
};
// Carousel Previous
document.getElementsByClassName("carousel")[i]._prev = function() {
// Index all Carousel Slides
for (var j = 0; j < this.querySelector(".slides-container").children.length; j++)
// Show the previous slide in the set
if (this.querySelector(".slides-container").children[j].hidden == false) {
this.querySelector(".slides-container").children[j].hidden = true;
(this.querySelector(".slides-container").children[j].previousElementSibling || this.querySelector(".slides-container").children[this.querySelector(".slides-container").children.length - 1]).hidden = false;
break
}
};
// Carousel Toggle
document.getElementsByClassName("carousel")[i]._toggle = function(slideIndex) {
// Index all Carousel Slides
for (var j = 0; j < this.querySelector(".slides-container").children.length; j++)
// Hide them
this.querySelector(".slides-container").children[j].hidden = true;
// Show the specified slide
(this.querySelector(".slides-container").children[slideIndex] || document.createElement("div")).hidden = false
};
// If the Carousel Interval is a Number
if (typeof document.getElementsByClassName("carousel")[i]._interval == "number") {
// Index
var index = i;
// Set an interval to automate the Carousel
setInterval(function() {
// If the Carousel direction is right
if (document.getElementsByClassName("carousel")[index]._direction == "right")
document.getElementsByClassName("carousel")[index]._next();
// If the Carousel direction is left
else if (document.getElementsByClassName("carousel")[index]._direction == "left")
document.getElementsByClassName("carousel")[index]._prev()
}, document.getElementsByClassName("carousel")[i]._interval)
}
// If the Carousel has buttons
if (document.getElementsByClassName("carousel")[i].hasAttribute("data-buttons"))
// Make the Buttons Container
document.getElementsByClassName("carousel")[i].innerHTML += (
'<div class="buttons-container">' +
'<button onclick="this.parentNode.parentNode._prev()"> Previous </button>' +
'<button onclick="this.parentNode.parentNode._next()"> Next </button>' +
'</div>'
)
// If the Carousel has indicators
if (document.getElementsByClassName("carousel")[i].hasAttribute("data-indicators"))
// Make the Indicators Container
document.getElementsByClassName("carousel")[i].innerHTML += (
'<div class="indicators-container">' +
// Place as many checkboxes for as many slides there are
(function() {
var indicators = "";
for (var k = 0; k < document.getElementsByClassName("carousel")[i].querySelector(".slides-container").children.length; k++)
indicators += (
'<input class="indicator-' + k + '" onclick="this.parentNode.parentNode._toggle(this.getAttribute(\'class\')[this.getAttribute(\'class\').length - 1])" type="checkbox">'
);
return indicators
})() +
'</div>'
);
// Add a click event to the Carousel
document.getElementsByClassName("carousel")[i].addEventListener("click", function() {
// Index all Carousel
for (var j = 0; j < document.getElementsByClassName("carousel").length; j++)
// If the Carousel indexed is not the target Carousel
if (document.getElementsByClassName("carousel")[j] != this)
// Blur it
document.getElementsByClassName("carousel")[j].removeAttribute("data-focus");
else
// 'Focus' it
document.getElementsByClassName("carousel")[j].setAttribute("data-focus", "")
// If the mouse click is to the left of the carousel
if (event.clientX < (this.getBoundingClientRect().left + (this.getBoundingClientRect().width / 2)))
this._prev();
// If the mouse click is to the right of the carousel
else if ((event.clientX > (this.getBoundingClientRect().left + (this.getBoundingClientRect().width / 2))))
this._next()
})
};
// Attach an event to the <body>.
document.body.addEventListener("keydown", function() {
switch (event.code) {
// If the left arrow key is pressed
case "ArrowLeft":
document.querySelector(".carousel[data-focus")._prev();
break;
// If the right arrow key is pressed
case "ArrowRight":
document.querySelector(".carousel[data-focus")._next();
break;
}
})
in this section of the code for the Carousel, the .hidden property can be replaced with anything else but it gives a basic idea of how the slides pass on through the active and inactive states.
as for the HTML part
<html>
<body>
<div class="carousel" data-active="1" data-auto="right_1" data-buttons data-indicators style="height: 300px">
<div style="background: #F00; color: #FFF; font-size: 50px; height: 100%; line-height: 300px; text-align: center"> R </div>
<div style="background: #0F0; color: #FFF; font-size: 50px; height: 100%; line-height: 300px; text-align: center"> G </div>
<div style="background: #00F; color: #FFF; font-size: 50px; height: 100%; line-height: 300px; text-align: center"> B </div>
</div>
<!-- The JS script for the Carousel -->
<script src="carousel.js"> </script>
</body>
</html>
Everything has been simplified:
the class of carousel to make a new Carousel,
data-active attribute to state which slide is active (starts from 0),
the data-auto attribute which specifies if the Carousel is automated or not (the right_ stands for the direction the automation and the _1 for how long the interval is),
the data-buttons attribute if buttons are required,
data-indicators if Carousel indicators are required and
the slides as the children of the Carousel.
So yes, this is pretty much the HTML/JS code required for building a simple Carousel.
In case you're looking for anything exciting going on in the world of JavaScript, there is a library I'm working on that I think you might be interested in: https://github.com/LapysDev/LapysJS.
tru use Slick galleries, it is better amounth any galleries
http://kenwheeler.github.io/slick/
The following should fix your slide issue. I added some code to the CSS and JS ensuring the slide will move at one slide and worked on smaller screen resolution also.
The JS:
The CSS:
The HTML: I left it unchanged, so just use the same HTML you have. Best regards.
When setting/getting values in a collection of elements, it's best to use .map(). Here's the answer in 50 lines (view on CodePen):
$(".faculty-carousel").map(function() {
// Use that to refer to the child nodes of each carousel object instance
var that = $(this),
slides = that.find(".faculty-items li"),
carousel = that.find(".faculty-items"),
prevBtn = that.find(".prev"),
nextBtn = that.find(".next"),
slideLen = slides.length,
slideCount = slideLen - 1;
// Set reference point for carousel movements. The .is-active class will always
// be applied to the activeSlide, providing a reliable method for maintaining
// the carousel's state.
slides.first().addClass("is-active");
// Shift in response to user click. Accepts optional direction argument
var shiftCarousel = function(direction) {
var target = that.find(".is-active");
var currentSlide = target.attr("data-slide");
if (direction === "left" && currentSlide > 0) {
currentSlide--;
target.removeClass("is-active").prev().addClass("is-active");
}
if (direction === "right" && currentSlide < slideCount) {
currentSlide++;
target.removeClass("is-active").next().addClass("is-active");
}
var transformPercentage = -1 * currentSlide / slideLen * 100;
carousel.css("transform", "translateX(" + transformPercentage + "% )");
};
var x = 0;
// Get position of each slide and store it in an HTML attribute
slides.each(function() {
$(this).attr("data-slide", "" + x++ + "");
$(this).click(function() {
$(this).addClass("is-active").siblings().removeClass("is-active");
// Invoke shiftCarousel() without a parameter
shiftCarousel();
});
});
// Invoke shiftCarousel() with a parameter
prevBtn.on("click", function() {
shiftCarousel("left");
});
nextBtn.on("click", function() {
shiftCarousel("right");
});
// to manage mobile events, you can reference events via Hammer API
// or JavaScript's built-in touchstart, touchcancel etc. events i.e.
// prevBtn.on('touchstart', function() {
// do something
// });
});
It's better to stick with jQuery here. Oluwafunmito's solution uses innerHTML, which is the only practical technique if using vanilla JS. However, innerHTML can inadvertently expose your website visitors to an XSS attack and should be avoided whenever possible.
You can use swiper. most modern mobile touch slider with hardware accelerated transitions and amazing native behaviour.
Instead of going through your whole code I can provide you with a fully functional carousel code using bootstrap and JavaScript. maybe this will give a hint about where your program is lacking and a bit of help in unerring your code.
<div id="mycarousel" class="carousel slide" data-interval="3000" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#mycarousel" data-slide-to="0" class="active"></li>
<li data-target="#mycarousel" data-slide-to="1"></li>
<li data-target="#mycarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img class="img-responsive"
src="img/uthappizza.png" alt="Uthappizza">
<div class="carousel-caption">
<h2>Uthappizza <span class="label label-danger">Hot</span> <span class="badge">$4.99</span></h2>
<p>A unique combination of Indian Uthappam (pancake) and
Italian pizza, topped with Cerignola olives, ripe vine
cherry tomatoes, Vidalia onion, Guntur chillies and
Buffalo Paneer.</p>
<p><a class="btn btn-primary btn-xs" href="#">More »</a></p>
</div>
</div>
<div class="item">
<img class="media-object img-thumbnail"
src="img/buffet.png" alt="Buffet">
<div class="carousel-caption">
<h2>Weekend Grand Buffet <span class="label label-danger">New</span> </h2>
<p>Featuring mouthwatering combinations with a choice of five different salads,
six enticing appetizers, six main entrees and five choicest desserts.
Free flowing bubbly and soft drinks. All for just $19.99 per person</p>
<p><a class="btn btn-primary btn-xs" href="#">More »</a></p>
</div>
</div>
<div class="item">
<img class="media-object img-thumbnail"
src="img/alberto.png" alt="Alberto Somayya">
<div class="carousel-caption">
<h2 >Alberto Somayya</h2>
<h4>Executive Chef</h4>
<p>Award winning three-star Michelin chef with wide
International experience having worked closely with
whos-who in the culinary world, he specializes in
creating mouthwatering Indo-Italian fusion experiences.
</p>
<p><a class="btn btn-primary btn-xs" href="#">More »</a></p>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
<div class="btn-group" id="carouselButtons">
<button class="btn btn-danger btn-sm" id="carousel-pause">
<span class="fa fa-pause" aria-hidden="true"></span>
</button>
<button class="btn btn-danger btn-sm" id="carousel-play">
<span class="fa fa-play" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
JavaScript
<script>
$('.carousel').carousel('pause')
</script>
<script>
$(".btn-group > .btn").click(function(){
$(this).addClass("active").siblings().removeClass("active");
});
</script>
<script>
$(document).ready(function(){
//$("#mycarousel").carousel( { interval: 2000 } );
$("#carousel-pause").click(function(){
$("#mycarousel").carousel('pause');
});
$("#carousel-play").click(function(){
$("#mycarousel").carousel('cycle');
});
});
</script>
credits:coursera
Your using the .each on all of the slides on all of the carousels, setting up a pan event and animation for each slide. Try only binding your function (and the included pan) on $('.faculty-carousel').each

Setting threshold on max number of classes selected/activated on click on multiple divs/id's

I've been working on a skill tree 'persay' and I ran into an interesting problem.
I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.
My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.
var skillTotal = 0;
var skillSelected = 0;
$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
var threshold = 4;
var price = 1;
if ($(this).hasClass('selected')) {
skillTotal = skillTotal - 1;
skillSelected--;
$(this).toggleClass('selected');
}
else if (price + skillTotal <= threshold) {
skillTotal = skillTotal + price;
skillSelected++;
$(this).toggleClass('selected');
}
});
$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
var threshold = 4;
var price = 1;
if ($(this).hasClass('selected')) {
skillTotal = skillTotal - 1;
skillSelected--;
$(this).toggleClass('selected');
}
else if (price + skillTotal <= threshold) {
skillTotal = skillTotal + price;
skillSelected++;
$(this).toggleClass('selected');
}
});
/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
var campThreshold = 3;
var campPrice = 1;
if ($(this).hasClass('selected')) {
campTotal = campTotal - campPrice;
selectedCamp--;
$(this).toggleClass('selected');
}
else if (campPrice + campTotal <= campThreshold) {
campTotal = campTotal + campPrice;
selectedCamp++;
$(this).toggleClass('selected');
}
}); */
.skill-slot, .camp-slot{
border:2px solid black;
width:100px;
margin: 5px;
opacity: .4;
}
.skill-slot:hover, .camp-slot:hover {
opacity: 1;
}
.raffle-slot.taken{
background:red;
}
.selected{
background: rgb(255, 128, 128);
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calc">
<ol class="roster" id="selectable01">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
<ol class="roster" id="selectable02">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
</div>
Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on
The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.
A way simpler approach using Event delegation. Toggle .selected to either deactivate the current .skill-slot, or to activate it if there are less than 4 .selected.skill-slots in this group.
$('#selectable01, #selectable02').on('click', '.skill-slot', function(e){
if($(this).hasClass('selected') || $('.selected.skill-slot', e.delegateTarget).length < 4){
$(this).toggleClass('selected');
}
});
.skill-slot, .camp-slot{
border:2px solid black;
width:100px;
margin: 5px;
opacity: .4;
}
.skill-slot:hover, .camp-slot:hover {
opacity: 1;
}
.raffle-slot.taken{
background:red;
}
.selected{
background: rgb(255, 128, 128);
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calc">
<ol class="roster" id="selectable01">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
<ol class="roster" id="selectable02">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
</div>
As you are using global variables for the count and total, this obviously leads to a global limit. To make the limit local to each of the groups, you could use data attributes of these ol elements, so they work independently from each other. With some other little improvements, your code could look like this:
$("#selectable01, #selectable02").data("skillTotal", 0).data("skillSelected", 0);
$("#selectable01>li.skill-slot,#selectable02>li.skill-slot").on("click", function () {
var threshold = 4,
price = 1,
sign = $(this).hasClass('selected') ? -1: 1,
$p = $(this).parent(),
newPrice = $p.data("skillTotal") + sign*price;
if (newPrice > threshold) return;
$p.data("skillTotal", newPrice)
.data("skillSelected", $p.data("skillSelected") + sign);
$(this).toggleClass('selected');
});
.skill-slot, .camp-slot{
border:2px solid black;
width:100px;
margin: 5px;
opacity: .4;
}
.skill-slot:hover, .camp-slot:hover {
opacity: 1;
}
.raffle-slot.taken{
background:red;
}
.selected{
background: rgb(255, 128, 128);
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calc">
<ol class="roster" id="selectable01">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
<ol class="roster" id="selectable02">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>
</div>
You're storing skillSelected outside of the event handlers so each event handler is reading that variable. You might need to get a running total of how many are selected each time the event handler is triggered.

Reduce the gap between two blocks in CSS

Im working on a project and I got to a part where Im supposed to reduce the gap between the blocks to 3px. I have tried my best the last 2 days but i can not get the desired display.
This a screen capture of what have done:
Screen Capture of the page
Im not able to run snippet when I paste my codes in this post so I will just give out the needed code for you to provide me your help.
(function($) {
var aux = {
// navigates left / right
navigate : function( dir, $el, $wrapper, opts, cache ) {
var scroll = opts.scroll,
factor = 1,
idxClicked = 0;
if( cache.expanded ) {
scroll = 1; // scroll is always 1 in full mode
factor = 3; // the width of the expanded item will be 3 times bigger than 1 collapsed item
idxClicked = cache.idxClicked; // the index of the clicked item
}
// clone the elements on the right / left and append / prepend them according to dir and scroll
if( dir === 1 ) {
$wrapper.find('div.ca-item:lt(' + scroll + ')').each(function(i) {
$(this).clone(true).css( 'left', ( cache.totalItems - idxClicked + i ) * cache.itemW * factor + 'px' ).appendTo( $wrapper );
});
}
else {
var $first = $wrapper.children().eq(0);
$wrapper.find('div.ca-item:gt(' + ( cache.totalItems - 1 - scroll ) + ')').each(function(i) {
// insert before $first so they stay in the right order
$(this).clone(true).css( 'left', - ( scroll - i + idxClicked ) * cache.itemW * factor + 'px' ).insertBefore( $first );
});
}
// animate the left of each item
// the calculations are dependent on dir and on the cache.expanded value
$wrapper.find('div.ca-item').each(function(i) {
var $item = $(this);
$item.stop().animate({
left : ( dir === 1 ) ? '-=' + ( cache.itemW * factor * scroll ) + 'px' : '+=' + ( cache.itemW * factor * scroll ) + 'px'
}, opts.sliderSpeed, opts.sliderEasing, function() {
if( ( dir === 1 && $item.position().left < - idxClicked * cache.itemW * factor ) || ( dir === -1 && $item.position().left > ( ( cache.totalItems - 1 - idxClicked ) * cache.itemW * factor ) ) ) {
// remove the item that was cloned
$item.remove();
}
cache.isAnimating = false;
});
});
},
// opens an item (animation) -> opens all the others
openItem : function( $wrapper, $item, opts, cache ) {
cache.idxClicked = $item.index();
// the item's position (1, 2, or 3) on the viewport (the visible items)
cache.winpos = aux.getWinPos( $item.position().left, cache );
$wrapper.find('div.ca-item').not( $item ).hide();
$item.find('div.ca-content-wrapper').css( 'left', cache.itemW + 'px' ).stop().animate({
width : cache.itemW * 2 + 'px',
left : cache.itemW + 'px'
}, opts.itemSpeed, opts.itemEasing)
.end()
.stop()
.animate({
left : '0px'
}, opts.itemSpeed, opts.itemEasing, function() {
cache.isAnimating = false;
cache.expanded = true;
aux.openItems( $wrapper, $item, opts, cache );
});
},
// opens all the items
openItems : function( $wrapper, $openedItem, opts, cache ) {
var openedIdx = $openedItem.index();
$wrapper.find('div.ca-item').each(function(i) {
var $item = $(this),
idx = $item.index();
if( idx !== openedIdx ) {
$item.css( 'left', - ( openedIdx - idx ) * ( cache.itemW * 3 ) + 'px' ).show().find('div.ca-content-wrapper').css({
left : cache.itemW + 'px',
width : cache.itemW * 2 + 'px'
});
// hide more link
aux.toggleMore( $item, false );
}
});
},
// show / hide the item's more button
toggleMore : function( $item, show ) {
( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide();
},
// close all the items
// the current one is animated
closeItems : function( $wrapper, $openedItem, opts, cache ) {
var openedIdx = $openedItem.index();
$openedItem.find('div.ca-content-wrapper').stop().animate({
width : '0px'
}, opts.itemSpeed, opts.itemEasing)
.end()
.stop()
.animate({
left : cache.itemW * ( cache.winpos - 1 ) + 'px'
}, opts.itemSpeed, opts.itemEasing, function() {
cache.isAnimating = false;
cache.expanded = false;
});
// show more link
aux.toggleMore( $openedItem, true );
$wrapper.find('div.ca-item').each(function(i) {
var $item = $(this),
idx = $item.index();
if( idx !== openedIdx ) {
$item.find('div.ca-content-wrapper').css({
width : '0px'
})
.end()
.css( 'left', ( ( cache.winpos - 1 ) - ( openedIdx - idx ) ) * cache.itemW + 'px' )
.show();
// show more link
aux.toggleMore( $item, true );
}
});
},
// gets the item's position (1, 2, or 3) on the viewport (the visible items)
// val is the left of the item
getWinPos : function( val, cache ) {
switch( val ) {
case 0 : return 1; break;
case cache.itemW : return 2; break;
case cache.itemW * 2 : return 3; break;
}
}
},
methods = {
init : function( options ) {
if( this.length ) {
var settings = {
sliderSpeed : 500, // speed for the sliding animation
sliderEasing : 'easeOutExpo',// easing for the sliding animation
itemSpeed : 500, // speed for the item animation (open / close)
itemEasing : 'easeOutExpo',// easing for the item animation (open / close)
scroll : 1 // number of items to scroll at a time
};
return this.each(function() {
// if options exist, lets merge them with our default settings
if ( options ) {
$.extend( settings, options );
}
var $el = $(this),
$wrapper = $el.find('div.ca-wrapper'),
$items = $wrapper.children('div.ca-item'),
cache = {};
// save the with of one item
cache.itemW = $items.width();
// save the number of total items
cache.totalItems = $items.length;
// add navigation buttons
if( cache.totalItems > 3 )
$el.prepend('<div class="ca-nav"><span class="ca-nav-prev">Previous</span><span class="ca-nav-next">Next</span></div>')
// control the scroll value
if( settings.scroll < 1 )
settings.scroll = 1;
else if( settings.scroll > 3 )
settings.scroll = 3;
var $navPrev = $el.find('span.ca-nav-prev'),
$navNext = $el.find('span.ca-nav-next');
// hide the items except the first 3
$wrapper.css( 'overflow', 'hidden' );
// the items will have position absolute
// calculate the left of each item
$items.each(function(i) {
$(this).css({
position : 'absolute',
left : i * cache.itemW + 'px'
});
});
// click to open the item(s)
$el.find('a.ca-more').live('click.contentcarousel', function( event ) {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
$(this).hide();
var $item = $(this).closest('div.ca-item');
aux.openItem( $wrapper, $item, settings, cache );
return false;
});
// click to close the item(s)
$el.find('a.ca-close').live('click.contentcarousel', function( event ) {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
var $item = $(this).closest('div.ca-item');
aux.closeItems( $wrapper, $item, settings, cache );
return false;
});
// navigate left
$navPrev.bind('click.contentcarousel', function( event ) {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
aux.navigate( -1, $el, $wrapper, settings, cache );
});
// navigate right
$navNext.bind('click.contentcarousel', function( event ) {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
aux.navigate( 1, $el, $wrapper, settings, cache );
});
// adds events to the mouse
$el.bind('mousewheel.contentcarousel', function(e, delta) {
if(delta > 0) {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
aux.navigate( -1, $el, $wrapper, settings, cache );
}
else {
if( cache.isAnimating ) return false;
cache.isAnimating = true;
aux.navigate( 1, $el, $wrapper, settings, cache );
}
return false;
});
});
}
}
};
$.fn.contentcarousel = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.contentcarousel' );
}
};
})(jQuery);
/* Circular Content Carousel Style */
/*Three points are very important when we want the image to fit the space required: by default: .ca-container{width:1205px;}, .ca-item{width:410px;}, .ca-item-main{width:380px;} */
.ca-container{
position:relative;
margin:25px auto 20px auto;
width:1205px;
height:650px;
}
.ca-wrapper{
width:100%;
height:100%;
position:relative;
}
.ca-item{
position:relative;
float:left;
width:410px;
height:100%;
text-align:center;
}
.ca-item-main{
position:absolute;
width: 380px;
top:5px;
left:5px;
right:5px;
bottom:5px;
background:#fff;
overflow:hidden;
-moz-box-shadow:1px 1px 2px rgba(0,0,0,0.2);
-webkit-box-shadow:1px 1px 2px rgba(0,0,0,0.2);
box-shadow:1px 1px 2px rgba(0,0,0,0.2);
}
.ca-nav span{
width:25px;
height:38px;
background:transparent url(../images/arrows.png) no-repeat top left;
position:absolute;
top:50%;
margin-top:-19px;
left:-40px;
text-indent:-9000px;
opacity:0.7;
cursor:pointer;
z-index:100;
}
.ca-nav span.ca-nav-next{
background-position:top right;
left:auto;
right:-40px;
}
.ca-nav span:hover{
opacity:1.0;
}
/*Text over image*/
h2.header {
bottom: 0;
position: absolute;
text-align: center;
margin: 0;
width: 100%;
background-color: rgba(0,0,0,0.7);
padding: 35px 0px 35px 0px;
font-family: FeaturedItem;
}
.wrapper {
display: inline-block;
position: relative;
}
.wrapper img {
display: block;
max-width:100%;
}
.wrapper .overlay {
position: absolute;
top:0;
left:0;
width:380px;
height:100%;
color:white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Circular Content Carousel with jQuery</title>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div class="container">
<div id="ca-container" class="ca-container">
<div class="ca-wrapper">
<div class="ca-item ca-item-1">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/2.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-2">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/5.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-3">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/6.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-4">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/2.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-5">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/5.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-6">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/6.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-7">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/2.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
<div class="ca-item ca-item-8">
<div class="ca-item-main">
<div class="wrapper">
<img src="images/5.jpg" alt="" />
<div class="overlay">
<h2 class="header">A Movie in the Park: Kung Fu Panda</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<!-- the jScrollPane script -->
<script type="text/javascript" src="js/jquery.contentcarousel.js"></script>
<script type="text/javascript">
$('#ca-container').contentcarousel();
</script>
</body>
</html>
If anybody need to run the code in local then a .zip file is here: https://www.dropbox.com/s/x0pgyk8mbplgih0/carousel.zip?dl=0
please let me know how to solve this problem. Thanks in advance.
I really believe you couldn't post your code here. even I couldn't clone it on jsfiddle ! but rules are rules!
anyway, you can fix your issue with this:
.ca-item-main {
position: absolute;
width: 405px;
top: 5px;
left: 5px;
right: 5px;
bottom: 5px;
background: #fff;
overflow: hidden;
-moz-box-shadow: 1px 1px 2px rgba(0,0,0,0.2);
-webkit-box-shadow: 1px 1px 2px rgba(0,0,0,0.2);
box-shadow: 1px 1px 2px rgba(0,0,0,0.2);
}
.wrapper {
display: inline-block;
position: relative;
width: 100%;
}
.wrapper img {
display: block;
min-width: 100%;
}
.ca-container {
position: relative;
margin: 25px auto 20px auto;
width: 1230px;
height: 650px;
}

jQuery: How to make clicking anywhere outside of left menu close said window?

There is a menu button on the left of my site in progress.
This is the Javascript code which opens the menu:
var main = function()
$('.icon-menu').click(function() {
$('.menu').animate({
left: "0px"
}, 400);
$('body').animate({
left: "285px"
}, 400);
});
And this is the Javascript code which closes the menu:
$('.icon-close').click(function () {
$('.menu').animate({
left: "-285px"
}, 400);
$('body').animate({
left: "0px"
}, 400);
});
What I would like to be able to do is, instead of using a "close" icon, I would like for a click anywhere on the page (including the original menu button) to close the menu.
As the code is currently written, when the menu is opened/closed, it slides in from the left, and the main body of the page slides to the right the same amount of pixels, and vice-versa when closed.
EDIT:
Here's the skeleton of the HTML as requested:
<div class="menu">
<div class="icon-close">
<img src="close.png">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div class="jumbotron">
<div class="icon-menu">
<i class="fa fa-bars"></i>Menu
</div>
</div>
You can capture a document.onclick event then check the event target id against a set of allowed id's Note that to do this you have to add id attributes to the close button and the "body". I've also taken the liberty of adding an id to the menu and a wrapper around the "body" of the document and changed your body tag animation to that wrapper, as you shouldnt move the body tag directly. Note that to resize the body on menu open just change the body position: absolute and set right: 0px;
(Demo keep body size on menu open)
(Demo resize body to keep within viewport on menu open)
$(document).on('click', function(e) {
if ($("#menu").position().left != '0') {
if (e.target.id === "open") {
$('#menu').animate({
left: "0px"
}, 400);
$('#body').animate({
left: "285px"
}, 400);
}
} else {
if (e.target.id === "body" || e.target.id === "close" || e.target.id === "open") {
$('#menu').animate({
left: "-285px"
}, 400);
$('#body').animate({
left: "0px"
}, 400);
}
}
});
html, body, #menu, #body {
height: 100%;
}
.menu {
position: absolute;
width: 285px;
left: -285px;
}
#body {
position: relative;
left: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu" id="menu">
<div class="icon-close">
<img src="close.png" id="close">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div id="body">
<div class="jumbotron">
<div class="icon-menu" id="open">
<i class="fa fa-bars" id="open"></i>Menu
</div>
</div>
</div>
Pure JS and CSS
The following is a pure javascript and css method for achieving the same effect. I'm including this for reference as it is a lot lighter weight than including jquery, however if you have jquery included already there is no reason to not use the jquery methods. Notice that on older browsers that do not support css transitions the menu will still open but will not be animated (which is a good thing for older browsers as javascript animations can slow things down quite a bit)
(Demo keep body size on menu open)
(Demo resize body to keep within viewport on menu open)
var menu = document.getElementById("menu");
var body = document.getElementById("body");
menu.style.transition = "0.3s linear";
body.style.transition = "0.3s linear";
document.onclick = function(e) {
if (menu.style.left != "0px") {
if (e.target.id === "open") {
menu.style.left = "0px";
body.style.left = "285px";
}
} else {
if (e.target.id === "body" || e.target.id === "close" || e.target.id === "open") {
menu.style.left = "-285px";
body.style.left = "0px";
}
}
};
html, body, #menu, #body {
height: 100%;
}
.menu {
position: absolute;
width: 285px;
left: -285px;
}
#body {
position: relative;
left: 0px;
}
<div class="menu" id="menu">
<div class="icon-close">
<img src="close.png" id="close">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div id="body">
<div class="jumbotron">
<div class="icon-menu" id="open">
<i class="fa fa-bars" id="open"></i>Menu
</div>
</div>
</div>
Here's humble's version of the snippet below:
http://jsfiddle.net/humbleRumble/3j7s9ggz/
You can just bind a click event to the document that does the same thing as the click on the close button:
$(document).on('click', function (e) {
// Filter some elements out so that this function doesn't
// execute when it's not intended to.
var target = e.target,
isMenuElem = $(target).parents('.menu').length || $(target).is('.menu'),
isMenuClose = $('.icon-close').has(target).length,
isIconMenu = $(target).is('.icon-menu');
// Simply return if the clicked element falls under the filter.
// This allows the close button to close,
// the menu to not close itself if you click its body,
// the function to not interfere with the menu button functionality,
// and that a click on anywhere will close the menu.
if (isMenuElem && !isMenuClose || isIconMenu) return;
$('.menu, #jumbotron').animate({
left: "-285px"
}, 400);
});
$('.icon-menu').click(function () {
// This is a 'toggle' value for left,
// if the menu is opened (left: 0), close it (left: -285)
// and vice-versa.
var toggleAnim = $('.menu').css('left') === '-285px' ? 0 : '-285px';
$('.menu, #jumbotron').animate({
// Apply the toggle
left: toggleAnim
}, 400);
});
html, body {
padding: 0;
margin: 0;
}
#jumbotron {
position: relative;
height: 500px;
width: 300px;
float: left;
}
.menu {
position: relative;
width: 285px;
height: 500px;
background: red;
float: left;
}
.icon-menu {
background: black;
color: #fff;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<div class="icon-close">
<img src="close.png" alt="Close Me">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div class="jumbotron" id="jumbotron">
<div class="icon-menu">
<i class="fa fa-bars"></i>Menu
</div>
</div>
This will trigger with a click anywhere on the page, but not on the elements inside of the menu (except the close button).

Categories