So I am trying to achieve the effect as such on this website.
(Near the bottom where you can hover over the image and it shows another as you move over it)
Any ideas? I mean I know they are just overlaying the two images, but how they then display the far image using CSS/Javascript on hover? This is beyond me. I have tried reproducing it myself with no success.
Try this:
var main = document.querySelector('.main');
var one = document.querySelector('.one');
var two = document.querySelector('.two');
main.onmousemove = function (e) {
var width = e.pageX - e.currentTarget.offsetLeft;
one.style.width = width + "px";
two.style.left = width + "px";
}
.main {
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
.one {
background-image: url('http://www.lorempixel.com/200/200');
width: 50%;
height: 100%;
}
.two {
background-image: url('http://www.lorempixel.com/200/200/sports');
position: absolute;
left: 50%;
right: 0px;
top: 0px;
bottom: 0px;
background-position: right;
}
<div class="main">
<div class="one"></div>
<div class="two"></div>
</div>
Working Fiddle
So what's happening is, as the mouse hovers over the line, the width changes dynamically, if you inspect the element, you can see this as well.
Now, in the DOM structure, the brown car, the one being hidden is before the top image. So to achieve this, you can position the brown car absolutely, so it goes right behind the next image, and with javascript or jQuery add a listener for hover, on the image or that middle line that is used on the site, that will change the width of the top image (the silver one) in respect to the position of the mouse in the block of the image.
Essentially, the width of the background image should change by percentage to how far the mouse is from the left of the DIV, by percent i.e. if the mouse is at the middle, the width should be 50%.
Here is the js they use to do it, right from their site (I uncompressed it)
var ImageSlider = ImageSlider || {};
ImageSlider.Public = function(t) {
"use strict";
var e = t(".image-compare-tool"),
i = t(".image-compare-images"),
o = t(".image-compare-top img"),
a = (t(".image-compare-bottom img"), function(e) {
e.preventDefault();
var i, o = t(this).find(".image-compare-top"),
a = t(this).find(".image-compare-bottom img")[0],
n = a.getBoundingClientRect();
i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
width: i + "%"
})
}),
n = function() {
i.each(function() {
t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
})
},
m = function() {
o.each(function() {
var e = t(this).attr("src"),
i = t(this).parent();
i.css("background-image", "url(" + e + ")")
})
},
c = function() {
n(), m()
},
r = function() {
e.length > 0 && c()
};
r()}(jQuery);
If you look at html sources (Ctr + Shift + I in Chrome) you can see this element
<div class="image-compare-tool ICT-theverge">
<div class="image-compare-images">
<div class="image-compare-bottom"><img src="http://cdn2.vox-cdn.com/uploads/chorus_asset/file/2455624/khyzyl-saleem-plain-copylow.0.jpg"></div>
<div class="image-compare-top" style="width: 6.158357771261%; background-image: url(http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg);"><img src="http://cdn0.vox-cdn.com/uploads/chorus_asset/file/2455620/khyzyl-saleem-plain-copylow1.0.jpeg"></div>
</div>
</div>
So here are images! So next you need to look at css.
.image-compare-tool
{
max-width:100%;
width:100%;
z-index:999;
margin:0 auto 1.5em 0;
}
.image-compare-images
{
font-size:0;
position:relative;
height:100%;
-ms-touch-action:none;
-webkit-touch-callout:none;
-webkit-user-select:none;
}
.image-compare-images:hover
{
cursor:col-resize;
}
.image-compare-images img
{
display:block;
height:auto;
width:100%;
}
.image-compare-top,.image-compare-bottom
{
z-index:0;
height:100%;
}
.image-compare-top
{
background-size:cover;
height:100%;
left:0;
position:absolute;
top:0;
width:50%;
}
.image-compare-top:after
{
background-color:#fff;
content:'';
height:50px;
left:calc(100%-5px);
top:calc(50%-25px);
position:absolute;
width:10px;
}
.image-compare-top img
{
display:none;
}
.ICT-SBNation .image-compare-top:after
{
background-color:#c52126;
}
.ICT-SBNation .image-compare-top:before
{
background-color:#c52126;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.ICT-TheVerge .image-compare-top:after
{
background-color:#fa4b2a;
}
.ICT-TheVerge .image-compare-top:before
{
background-color:#fa4b2a;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.ICT-Polygon .image-compare-top:after
{
background-color:#ff0052;
}
.ICT-Polygon .image-compare-top:before
{
background-color:#ff0052;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
.image-compare-top:before,.ICT-Vox .image-compare-top:before
{
background-color:#fff;
content:'';
height:100%;
left:calc(100%-2.5px);
top:0;
position:absolute;
width:5px;
}
Here wea! You can implement same stuff by just including css and making same html structure and classes with just changing img paths...
And finally the js that i brazenly stole from the answer above:
var ImageSlider = ImageSlider || {};
ImageSlider.Public = function (t) {
"use strict";
var e = t(".image-compare-tool"),
i = t(".image-compare-images"),
o = t(".image-compare-top img"),
a = (t(".image-compare-bottom img"), function (e) {
e.preventDefault();
var i, o = t(this).find(".image-compare-top"),
a = t(this).find(".image-compare-bottom img")[0],
n = a.getBoundingClientRect();
i = "mousemove" == e.originalEvent.type ? (e.pageX - n.left) / a.offsetWidth * 100 : (e.originalEvent.touches[0].pageX - n.left) / a.offsetWidth * 100, 100 >= i && o.css({
width: i + "%"
})
}),
n = function () {
i.each(function () {
t(this).on("mousemove", a), t(this).on("touchstart", a), t(this).on("touchmove", a)
})
},
m = function () {
o.each(function () {
var e = t(this).attr("src"),
i = t(this).parent();
i.css("background-image", "url(" + e + ")")
})
},
c = function () {
n(), m()
},
r = function () {
e.length > 0 && c()
};
r()
}(jQuery);
And the working JSFiddle: http://jsfiddle.net/9gf59k00/
And my good luck...
$('img').on('mousemove', function(){
var imgsrc = $(this).attr('src');
if(imgsrc == 'img1.png'){
$(this).attr('src','img2.png');
}else{
$(this).attr('src','img1.png');
}
});
You can do this without javascript,
JSfiddle - http://jsfiddle.net/k4915wwm/
Just…
div:hover {
background:url("newImage.jpg");
}
Related
I have editable div with overflow set to hidden, I'd like the div to expand as the user types (if needed). II'm using jquery to change the class of the div each time the height changes.
I cant seem to get to work at all, it chnages the class but nothing happens
Fiddle
HTML:
<div class="contanier">
<div class="1" id="msgWriteArea" contenteditable="true"></div>
</div>
CSS:
#msgWriteArea{
outline: 0;
border: none;
resize: none;
width: 100%;
height:20px;
line-height:20px;
font-size:18px;
border:solid 1px #000;
background:#FFF;
}
.contanier .1{
height:20px;
overflow:hidden;
}
.contanier .2{
height:40px;
overflow:hidden;
}
.contanier .3{
height:60px;
overflow:hidden;
}
.contanier .4{
height:80px;
overflow:hidden;
}
.contanier .5{
height:80px;
overflow-y:scroll;
}
Javascript:
var chatBoxSize = {
oldHeight : 0,
scrollHeight : 0,
lastClass : 1,
maxClass : 5
};
function updateChatSize() {
var id = '#msgWriteArea';
var element = document.querySelector(id);
if((element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
if(chatBoxSize.lastClass == null){
//add size 1
console.log('ADD SIZE 1');
$(id).addClass('1');
chatBoxSize.lastClass = '1';
} else if(chatBoxSize.oldHeight != $(id)[0].scrollHeight){
//get the correct size to add
if(parseInt(current) >= parseInt(chatBoxSize.maxClass)){
var current = chatBoxSize.maxClass,
last = parseInt(chatBoxSize.maxClass) - 1;
chatBoxSize.lastClass = current;
console.log('IS AT MAX SIZE');
} else if(chatBoxSize.scrollHeight < $(id)[0].scrollHeight){
var current = parseInt(chatBoxSize.lastClass) + 1,
last = parseInt(chatBoxSize.lastClass);
chatBoxSize.lastClass = current;
} else if(chatBoxSize.scrollHeight > $(id)[0].scrollHeight) {
var current = parseInt(chatBoxSize.lastClass) - 1,
last = parseInt(chatBoxSize.lastClass);
chatBoxSize.lastClass = current;
} else {
//console.log('No Change in height');
}
if(last != undefined){
console.log('Add', current, 'Remove', last);
$('#msgWriteArea').addClass(current + "");
$('#msgWriteArea').removeClass(last + "");
$('#display').val('Add ' + current + ' Remove' + last);
}
}
chatBoxSize.oldHeight = element.offsetHeight;
chatBoxSize.scrollHeight = $(id)[0].scrollHeight;
chatBoxSize.oldHeight = element.offsetHeight;
}
};
$(function (){
$('#msgWriteArea').bind('change keydown input', function () {
if(event.type == 'keydown'){
updateChatSize();
}
});
});
This is part of a larger page. So would need to the class to change on other elements but just one for now to get the hang of how this works
You can do it by adding this CSS:
#msgWriteArea{
height: auto !important;
max-height: 80px; // Max Chat Box Size..
overflow-y: scroll;
}
See JsFiddle
if you set a fix height to contenteditable this won't expand vertically,
so to begin with remove height attribute;
then using line-height attribute instead of el.offsetHeight (in the evaluation for adding a class depending on height) should fix your fiddle;
fiddle
I am using the following to contain a div within borders.
The DIV is attached to each arrow key.
How can I change the background image of #body per each key-direction?
<script>
var pane = $('#border'),
box = $('#body'),
w = pane.width() - box.width(),
d = {},
x = 3;
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
</script>
<div id="border">
<div id="body">
<div class='head'></div>
</div>
</div>
#border{position:relative; width:300px; height:300px; border:2px solid red;}
#body{position:absolute; top:140px; left:140px; width: 70px; height: 70px; background: url('/images/model.png');}
#body .head{width: 70px; height: 25px; top: 0; background: rgba(0,0,0,0.5);}
Whenever any keypress/keydown events are fired change the background-image attribute using the css method of jquery.
$('.background').css('background-image','url(images/any_image.png)');
In your case it might be something like this,
$(window).keydown(function(e) {
d[e.which] = true;
$('#body').css('background-image','url(http://hdlatestwallpapers.com/wp-content/uploads/2013/12/Tom-and-Jerry-Cartoon-Wallpaper.jpg)');
});
Not sure how you are getting the images. If you can get random images on each keydown/keyup then you can change the url and have difference backgrounds. Same goes for keyup event.
CLICK FOR FIDDLE
Below is a fully functional full page touch slider I have created using hammer.js
You can drag, swipe or pan to navigate between pages.
The slider works as expected but I am now trying to create fallback navigation by adding two buttons so paging left and right can occur on click also.
QUESTION
How can the hammer swipe left or right be called on click? (Javascript or jQuery).
CURRENT ATTEMPT
$('#Left').on('click', function() {
HammerCarousel(document.querySelector('.Swiper'), 'Left');
});
FULL CODE
function swipe() {
var reqAnimationFrame = (function () {
return window[Hammer.prefixed(window, "requestAnimationFrame")] || function (callback) {
setTimeout(callback, 1000 / 60);
}
})();
function dirProp(direction, hProp, vProp) {
return (direction & Hammer.DIRECTION_HORIZONTAL) ? hProp : vProp
}
function HammerCarousel(container, direction) {
this.container = container;
this.direction = direction;
this.panes = Array.prototype.slice.call(this.container.children, 0);
this.containerSize = this.container[dirProp(direction, 'offsetWidth', 'offsetHeight')];
this.currentIndex = 0;
this.hammer = new Hammer.Manager(this.container);
this.hammer.add(new Hammer.Pan({ direction: this.direction, threshold: 10 }));
this.hammer.on("panstart panmove panend pancancel", Hammer.bindFn(this.onPan, this));
this.show(this.currentIndex);
}
HammerCarousel.prototype = {
show: function (showIndex, percent, animate) {
showIndex = Math.max(0, Math.min(showIndex, this.panes.length - 1));
percent = percent || 0;
var className = this.container.className;
if (animate) {
if (className.indexOf('animate') === -1) {
this.container.className += ' animate';
}
} else {
if (className.indexOf('animate') !== -1) {
this.container.className = className.replace('animate', '').trim();
}
}
var paneIndex, pos, translate;
for (paneIndex = 0; paneIndex < this.panes.length; paneIndex++) {
pos = (this.containerSize / 100) * (((paneIndex - showIndex) * 100) + percent);
translate = 'translate3d(' + pos + 'px, 0, 0)';
this.panes[paneIndex].style.transform = translate;
this.panes[paneIndex].style.mozTransform = translate;
this.panes[paneIndex].style.webkitTransform = translate;
}
this.currentIndex = showIndex;
},
onPan: function (ev) {
var delta = dirProp(this.direction, ev.deltaX, ev.deltaY),
percent = (100 / this.containerSize) * delta,
animate = false;
if (ev.type == 'panend' || ev.type == 'pancancel') {
if (Math.abs(percent) > 20 && ev.type == 'panend') {
this.currentIndex += (percent < 0) ? 1 : -1;
}
percent = 0;
animate = true;
}
this.show(this.currentIndex, percent, animate);
}
};
var outer = new HammerCarousel(document.querySelector('.Swiper'), Hammer.DIRECTION_HORIZONTAL);
};
$(swipe);
html,
body,
.Page,
.Swiper{
position:relative;
height:100%;
}
.Swiper{
background:#666;
overflow:hidden;
}
.Swiper.animate > .Page{
transition:all .3s;
-webkit-transition:all .3s;
}
.Page{
position:absolute;
top:0;
left:0;
height:100%;
width:100%;
padding:0 10px;
font:42px Arial;
color:#fff;
padding-top:10%;
text-align:center;
}
.Page:nth-child(odd) {
background:#b00;
}
.Page:nth-child(even) {
background:#58c;
}
#Left,
#Right{
position:absolute;
top:0;
height:50px;
width:50px;
background:#fff;
text-align:center;
font:16px/3em Arial;
cursor:pointer;
}
#Left{
left:0;
}
#Right{
right:0;
}
<script src="http://hammerjs.github.io/dist/hammer.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Swiper">
<div class="Page">PAGE 1<br/>DRAG LEFT</div>
<div class="Page">PAGE 2<br/>SWIPE ME</div>
<div class="Page">PAGE 3<br/>HOLD TO PAN</div>
<div class="Page">PAGE 4<br/>FLICK TO GO BACK</div>
</div>
<div id="Left">Left</div>
<div id="Right">Right</div>
I have crafted a jQuery solution for this that should satisfy the fallback you are looking for.
Some things to consider, though. In your example as well, page re-size is not accounted for. I have not done so in this either to remain consistent and solve the immediate issue, but you will notice I am grabbing the $('.Page').width(); as a variable in this solution. I would recommend re-assigning this value if you do account for re-sizing. Also, a mix of swiping/clicking will throw this off. I assume since you indicated this will be a fallback, the user will receive one of the two experiences. If not, we'll need a way to update tracker on swipe events as well.
You'll notice var tracker = { 'R': 0 }. While naming may not be the best, 'R' will account for how many right "swipes" (navigation clicks) the user has performed in a plus/minus 1 manner
<div id="Left" direction="L">Left</div>
<div id="Right" direction="R">Right</div>
$(function() {
var width = $('.Page').width();
var pages = $('.Page').length;
var tracker = { 'R': 0 }
$('#Right, #Left').click(function() {
$(this).attr('direction') === 'R' ?
((tracker.R < (pages - 1) ? tracker.R += 1 : pages)) :
(tracker.R > 0) ? (tracker.R -= 1) : 0;
$('.Swiper').animate({ 'scrollLeft': $('.Page').width() * tracker.R }, 250)
});
});
JSFiddle Link
I'm having a horizontal scrolling page where arrows are indicated to scroll. I'm using the following code which works fine.
HTML:
<div id="container">
<div id="parent">
<div class="contentBlock">1</div>
<div class="contentBlock">2</div>
<div class="contentBlock">3</div>
<div class="contentBlock">4</div>
<div class="contentBlock">5</div>
</div>
<span id="panLeft" class="panner" data-scroll-modifier='-1'>Left</span>
<span id="panRight" class="panner" data-scroll-modifier='1'>Right</span>
CSS:
#container{
width:600px;
overflow-x:hidden;
}
#parent {
width:6000px;
}
.contentBlock {
font-size:10em;
text-align:center;
line-height:400px;
height:400px;
width:500px;
margin:10px;
border:1px solid black;
float:left;
}
.panner {
border:1px solid black;
display:block;
position:fixed;
width:50px;
height:50px;
top:45%;
}
.active {
color:red;
}
#panLeft {
left:0px;
}
#panRight {
right:0px;
}
Javascript:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
}());
You can also view the code in a WordPress-Installation right here: http://ustria-steila.ch/test
The arrows and the scroll works really well - but I have different sites with different amounts of text and images. So some pages need a horizontal scroll and some not. How can I add some kind of if-condition to display the arrows only if there is a horizontal overflow?
Your JavaScript code should go like this:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
if(checkOverflow()){
$(".panner").show();
}
else
$(".panner").hide();
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
function checkOverflow()
{
var el=document.getElementById('container');
var curOverflow = el.style.overflowX;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflowX = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth;
el.style.overflowX = curOverflow;
return isOverflowing;
}
}());
Have worked out a solution, see the bottom!
I'm experimenting with a responsive carousel (fluid). I have elements stacked on top of each other so that the width can be fluid depending on the width of the parent. The issue is I need the parent to have overflow hidden which is not possible with children that are absolute positioned.
Tip on cleaning up the JS are appreciated too!
Does anyone have any ideas how to improve this or alternatives? Heres the fiddle: http://jsfiddle.net/j35fy/5/
.carousel-wrap {
position: relative;
}
.carousel-item {
position: absolute;
top: 0;
}
$.fn.mwCarousel = function(options) {
//Default settings.
var settings = $.extend({
changeWait: 3000,
changeSpeed: 800,
reveal: false,
slide: true,
autoRotate: true
}, options );
var CHANGE_WAIT = settings.changeWait;
var CHANGE_SPEED = settings.changeSpeed;
var REVEAL = settings.reveal;
var SLIDE = settings.slide;
var AUTO_ROTATE = settings.autoRotate;
var $carouselWrap = $(this);
var SLIDE_COUNT = $carouselWrap.find('.carousel-item').length;
var rotateTimeout;
if (AUTO_ROTATE) {
rotateTimeout = setTimeout(function(){
rotateCarousel(SLIDE_COUNT-1);
}, CHANGE_WAIT);
}
function rotateCarousel(slide) {
if (slide === 0) {
slide = SLIDE_COUNT-1;
rotateTimeout = setTimeout(function(){
$('.carousel-item').css('margin', 0);
$('.carousel-item').show();
}, CHANGE_WAIT);
if (REVEAL) {
$($carouselWrap.find('.carousel-item')[slide]).slideToggle(CHANGE_SPEED);
} else if (SLIDE) {
var carouselItem = $($carouselWrap.find('.carousel-item')[slide]);
carouselItem.show();
var itemWidth = carouselItem.width();
carouselItem.animate({margin: 0}, CHANGE_SPEED);
} else {
$($carouselWrap.find('.carousel-item')[slide]).fadeIn(CHANGE_SPEED);
}
slide = slide+1;
} else {
if (REVEAL) {
$($carouselWrap.find('.carousel-item')[slide]).slideToggle(CHANGE_SPEED);
} else if (SLIDE) {
var carouselItem = $($carouselWrap.find('.carousel-item')[slide]);
var itemWidth = carouselItem.width();
carouselItem.animate({marginLeft: -itemWidth, marginRight: itemWidth}, CHANGE_SPEED);
} else {
$($carouselWrap.find('.carousel-item')[slide]).fadeOut(CHANGE_SPEED);
}
}
rotateTimeout = setTimeout(function(){
rotateCarousel(slide-1);
}, CHANGE_WAIT);
}
}
$('.carousel-wrap').mwCarousel();
Solution
The first slide actually never moves (last one visible) so that one is set to position: static and all works nicely.
I think by just changing your CSS you're actually there:
.carousel-wrap {
position: relative;
overflow:hidden;
height:80%;
width:90%;
}
Demo: http://jsfiddle.net/robschmuecker/j35fy/2/
Discovered the solution is in fact simple, as the first slide in the DOM (the last you see) never actually moves itself I can set that one slide to be position: static and thus the carousel wrap will set it's height accordingly.
http://jsfiddle.net/j35fy/7/
.container {
background: aliceblue;
padding: 3em;
}
.carousel-wrap {
position: relative;
overflow:hidden;
}
.carousel-item:first-child {
position:static;
}
.carousel-item {
position: absolute;
top: 0;
width: 100%;
}
img {
width: 100%;
}