I've been trying to use a function to detect if an element is in the viewport:
function isElementInViewport (el) {
var rect = el[0].getBoundingClientRect();
return (rect.top>-1 && rect.bottom <= $(window).height());
}
var s= $('.special'),
y = $('.status');
$(window).on('scroll resize', function(){
if(isElementInViewport(s))
{
setTimeout(function(){
if(isElementInViewport(s))
{
var offer_id = s.data("offer-id");
alert(offer_id);
y.text('Yes');
}
}, 3000);
}
else
{
y.text('No');
}
});
Unfortunately this only seems to work for the first instance of the class 'special'. How do I get it to apply to all instances of that class?
Note that I've added a 3 second delay, to prevent fast scrolling from triggering it.
Here's the jsfiddle of my progress: http://jsfiddle.net/azjbrork/6/
using jquery each we can run the function on each instance of the .special class and report back accordingly (snippet below) :
function isElementInViewport(el) {
var rect = el[0].getBoundingClientRect();
return (rect.top > -1 && rect.bottom <= $(window).height());
}
var s = $('.special'),
y = $('.status');
$(window).on('scroll resize', function() {
s.each(function() {
var $this = $(this);
if (isElementInViewport($this)) {
setTimeout(function() {
if (isElementInViewport($this)) {
var offer_id = $this.data("offer_id");
// advise using an underscore instead of a hyphen in data attributes
// alert(offer_id); // reported in text below
y.text('Yes : ' + offer_id);
}
}, 200);
} else {
// y.text('No'); // omit this line otherwise it will always report no (subsequent out of screen divs will overwrite the response)
}
});
});
.special {
width: 80px;
height: 20px;
border: 1px solid #f90;
margin-top: 200px;
}
.status {
position: fixed;
right: 2em;
top: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='special' data-offer_id='a'></div>
<div class='special' data-offer_id='b'></div>
<div class='special' data-offer_id='c'></div>
<div class='special' data-offer_id='d'></div>
<div class='special' data-offer_id='e'></div>
<div class='special' data-offer_id='f'></div>
<div class='status'></div>
Related
To simplify this question I have created two divs: when you click on the orange box the blue box below it will move back and forth in a continuous loop. What I want to be able to do is:
Click the orange box to start and STOP the blue box loop
After starting and stopping, the blue box will stop and continue each time where it left off.
I've tried just about everything and can't get it to work. Any advice would be greatly appreciated.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
hoverSlideBox.onclick = function() {
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
init();
function init() {
setInterval(boxRight, 5);
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
You need to move some variables out of the onclick function so that they are not reset each time you click on the orange box. That, together with clearInterval, will give you a start/stop button.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var running = false;
var intervalId;
var pos = 0;
var moveLeft = false;
hoverSlideBox.onclick = function() {
init();
function init() {
if (!running) {
intervalId = setInterval(boxRight, 5);
running = true;
} else {
clearInterval(intervalId);
running = false;
}
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
To do this, you can use clearInterval to stop the movement. To make it resume when you click again, you just need to have your position variable in a permanent scope (I move it to the global scope for simplicity).
Changed code:
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
var slideInterval;
hoverSlideBox.onclick = function() {
init();
function init() {
if (slideInterval) {
clearInterval(slideInterval);
slideInterval = null;
} else {
slideInterval = setInterval(boxRight, 5);
}
}
Snippet:
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
var slideInterval;
hoverSlideBox.onclick = function() {
init();
function init() {
if (slideInterval) {
clearInterval(slideInterval);
slideInterval = null;
} else {
slideInterval = setInterval(boxRight, 5);
}
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
setInterval returns interval id which you can use to cancel the interval using clearInterval
You could cancel the timer as the other answer says, or use requestAnimationFrame which is specifically designed for animations like these. See documentation here
This way we can simply check if stopAnimating is set before queueing up our next frame. You could do the same thing with setInterval if you wanted to, but requestAnimationFrame is probably better.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
hoverSlideBox.onclick = function() {
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
init();
function init() {
animate();
}
function animate(){
// stop animating without queueing up thenext frame
if (stopAnimate) return;
//queue up theh next frame.
requestAnimationFrame(boxRight);
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
animate();
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
Your code doesn't clear the interval when box is clicked again. setInterval executes a function every number of given seconds. To stop it, you have use the function clearInterval, passing the timer id that the function setInterval returned.
Also, your code can be better organized. I've refactorized it base in the following advices:
Don't use different functions for each direction. Your code have two different functions (moveLeft and moveRight) that are almost the same. Instead, use a simpler function that increments position given the current direction. Use a simple variable with the position increment, using -1 for left movement and +1 for right movement. If you have to modify the way the box moves you only have to change the moveBox function.
Use a function to check if the box have reached the boundaries. In general is good to have small functions that do one simple thing. In your code, boundaries check is splited in the two movement functions. In the proposed code the check code is a separate function where you can modify boundaries easily in the future if needed, instead of changing them in different places of your code.
Don't put all your logic in the click listener. Again, use simple functions that perform one simple task. The click listener should do a simple task, that's switching animation on and off. Initialization code should be in its onw function.
Again, for simplicity, use a simple function as the function executed by setInterval. If not, you would have to change the function that is executed by the setInterval function: moveRight when box is moving to the right and moveLeft when the box is moving to the left. This makes the code more complex and hard to debug and mantain.
Those advices are not very useful with a small code like this, but its benefits are more visible when your code gets more complex.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var pos = 0;
var direction = 1;
var animate = false;
var intervalHandler;
hoverSlideBox.onclick = function() {
if (animate) {
stop();
}
else {
init();
}
}
function init() {
animate = true;
intervalHandler = setInterval(moveBox, 5);
}
function stop() {
animate = false;
clearInterval(intervalHandler);
}
function tic() {
if (animate) {
moveBox();
}
}
function checkBoundaries() {
if (pos == 500) {
direction = -1;
}
else if (pos == 0) {
direction = 1;
}
}
function moveBox() {
pos += direction;
slidingBox.style.left = pos + 'px';
checkBoundaries();
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
Try this snippet, it should work aswell
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var moveLeft = false;
var pos = 0;
var intervalID = null;
hoverSlideBox.onclick = function(){
if (intervalID) {
clearInterval(intervalID);
intervalID = null;
} else {
intervalID = setInterval(function () {
pos += moveLeft ? -1 : 1;
slidingBox.style.left = pos + 'px';
moveLeft = pos >= 500 ? true : pos <= 0 ? false : moveLeft;
}, 5);
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;">
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;">
I have a code that works just fine to check if element is outside of bottom viewport, as follows:
function posY(elm) {
let test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
let de = document.documentElement;
if(!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible (elm) {
let vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
if (hasActivity && isHidden) {
isVisibleCSS = <div className='onscreen'>More activity below ↓</div>;
} else if (hasActivity && !isHidden) {
//technically, there's no need for this here, but since I'm paranoid, let's leave it here please.
}
My question is, how can I adapt this code or create a new one similar to this one that identifies when element is outside of top viewport?
Cheers.
For an element to be completely off the view top then the sum of the element's top offset and it's height, like in this JS Fiddle
var $test = document.getElementById('test'),
$tOffset = $test.offsetTop,
$tHeight = $test.clientHeight,
$winH = window.innerHeight,
$scrollY;
window.addEventListener('scroll', function() {
$scrollY = window.scrollY;
if ($scrollY > ($tOffset + $tHeight)) {
console.log('out of the top');
}
});
body {
margin: 0;
padding: 0;
padding-top: 200px;
height: 1500px;
}
#test {
width: 100px;
height: 150px;
background-color: orange;
margin: 0 auto;
}
<div id="test"></div>
I am trying to develop the following carousel.
http://jsfiddle.net/2kLanjwn/2/
It should work in this way.
Clicking the button DOWN, carousel scrolls and resize always div in the center.
I am not able to apply the same logic on the reverse, so when I click button UP I need to contract the central div, and sliding up.
I kindly you what I am doing wrong and if you would be able to fix it on jsfiddle.
Also I would like to know if there is any better way to achieve that same effect or a component that can be reused.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Scroll text box example</title>
<style>
#btn-up, #btn-down {
position: absolute;
top: 600px;
}
#btn-up {
left: 0px;
}
#btn-down {
left: 50px;
}
#btn-up, #btn-down {
width: 50px;
height: 50px;
background-color: yellow;
outline: 1px solid black;
}
#content-scroll-container {
position: absolute;
top: 0;
left: 0px;
width: 500px;
height: 250px; /* MASK HEIGHT real mask would be 200*/
overflow: hidden;
}
#content-scroll-inner {
position: absolute;
}
.cnt {
height: 100px;
width: 500px;
background-color: red;
}
.cnt:nth-child(even) {
height: 100px;
background-color: pink;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var scroller = {
config: {
curPos: 0, // position
canExpand: false,
el: 'content-scroll-container', // visible area (container)
elInner: 'content-scroll-inner', // inner content
cntPosY: null, // content top-left corner (0 position)
cntHeight: null, // content lenght
maskHeight: null, // visible area (rest is masked out)
canMoveUp: null, // true jquery can slide up content
canMoveDown: null, // true jquery can slide down content
increment: 100, // slide of x pixel when user perfom an action
incrementOf: 0, // how much we have slided the contnt
animationSpeed: 500, // jquery animation speed, use 0 for no animation
isAnimationOn: false, // true when jquery is performing animation
},
data: '<div id="cnt-0" class="cnt">0</div><div id="cnt-1" class="cnt">1</div><div id="cnt-2" class="cnt">2</div><div id="cnt-3" class="cnt">3</div><div id="cnt-4" class="cnt">4</div><div id="cnt-5" class="cnt">5 empty</div>',
getCntPosition: function () {
// get y position of content
var elm = document.getElementById(this.config.elInner);
this.config.cntPosY = elm.offsetTop;
},
getCntSize: function () {
// get height for content
var elm = document.getElementById(this.config.elInner);
this.config.cntHeight = elm.clientHeight;
},
getMaskSize: function () {
// get height visible area
var elm = document.getElementById(this.config.el);
this.config.maskHeight = elm.clientHeight;
},
updateData: function () {
// refresh state
this.getMaskSize();
this.getCntPosition();
this.getCntSize();
this.canMoveUpCheck();
this.canMoveDownCheck();
//console.clear();
console.log(this.config);
},
canMoveUpCheck: function () {
// set flags allowing sliding up (in case we have enought content to show)
var lastScreenY = (this.config.cntHeight - this.config.maskHeight); // last screen visible
if ((this.config.incrementOf * -1) < lastScreenY)
this.config.canMoveUp = true;
else
this.config.canMoveUp = false;
},
canMoveDownCheck: function () {
// set flags allowing sliding down (in case we have enought content to show)
if (this.config.cntPosY >= 0)
this.config.canMoveDown = false; // cannot move more up if content is on start position (0 position)
else
this.config.canMoveDown = true;
},
goUp: function () {
// user want to read previose content
//this.updateData();
if (this.config.canMoveDown == true && this.config.isAnimationOn == false) {
this.moveCnt('down'); // content go down
}
},
goDown: function () { //**************************
// user want to read next content
//this.updateData();
if (this.config.canMoveUp == true && this.config.isAnimationOn == false) {
// check newPos
var newPos = this.config.curPos + 1;
if (newPos > 0) { // special case
if (this.config.canExpand == true)
this.config.increment = 150;
this.config.canExpand = true;
this.moveCnt('up');
}
}
},
moveCnt: function (direction) {
// do the actual animation
var moveOf;
this.isAnimationOn = true;
if (direction == 'up') {
this.config.curPos++;
if (this.config.cntPosY == 0) { // special case for first item
moveOf = '-=' + (this.config.increment / 2);
}
else {
moveOf = '-=' + this.config.increment;
}
var target = '#' + this.config.elInner + ':not(:animated)';
$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this, direction));
} else if (direction == 'down') {
this.config.curPos++;
var distanceToFp = (this.config.increment / 2); // height to reach first page (special page)
var distanceToFp = 50;
if (this.config.cntPosY == (distanceToFp * -1)) {
moveOf = '+=' + distanceToFp;
// i need to contract only the firs tone
$('cnt-1').css({ height: '100px' }, 500, this.cbEndAnimationExpand.bind(this));
} else {
moveOf = '+=' + this.config.increment;
}
var target = '#' + this.config.elInner + ':not(:animated)';
$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this));
}
//var target = '#' + this.config.elInner + ':not(:animated)';
//$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this, direction));
},
cbEndAnimation: function (direction) {
// runs when animation end
this.config.isAnimationOn = false;
if (direction == 'up') {
this.config.incrementOf -= this.config.increment;
if (this.config.canExpand == true) { // expand
this.logicExpand();
} else {
// do nothing
}
}
else if (direction == 'down') {
this.config.incrementOf += this.config.increment;
}
this.updateData(); // refresh state has element has just moved
this.logicShowHideArrows();
},
logicExpand: function () {
// take contenf and expand it
var elm = document.getElementById('cnt-' + this.config.curPos);
$(elm).animate({ height: '150px' }, 500, this.cbEndAnimationExpand.bind(this));
},
cbEndAnimationExpand: function () {
console.log('end anim expand');
},
logicContract: function () {
var elm = document.getElementById('cnt-' + this.config.curPos);
$(elm).animate({ height: '-=50px' }, 500, this.cbEndAnimationContract.bind(this));
},
logicShowHideArrows: function () {
// reset first
this.hideArrow('btn-up');
this.hideArrow('btn-down');
if (this.config.canMoveUp == true)
this.showArrow('btn-down');
if (this.config.canMoveDown == true)
this.showArrow('btn-up');
},
cbEndAnimationContract: function () {
this.config.isAnimationOn = false;
this.moveCnt('down'); // content go down
},
showArrow: function (elmName) {
var elm = document.getElementById(elmName);
elm.style.display = '';
},
hideArrow: function (elmName) {
var elm = document.getElementById(elmName);
elm.style.display = 'none';
},
setEventHandler: function () {
// envet handlers for arrows
var btnUp = document.getElementById('btn-up');
btnUp.addEventListener('click', this.goUp.bind(this), false);
var btnDown = document.getElementById('btn-down');
btnDown.addEventListener('click', this.goDown.bind(this), false);
},
renderData: function () {
// render data content to slide
var elm = document.getElementById(this.config.elInner);
elm.innerHTML = this.data;
},
start: function () {
this.renderData();
this.updateData();
this.setEventHandler();
this.logicShowHideArrows(); // at start set arrows visibility
}
};
</script>
</head>
<body onload="scroller.start();">
<div id="content-scroll-container">
<div id="content-scroll-inner">
</div>
</div>
<div id="btn-up">UP</div>
<div id="btn-down">DOWN</div>
</body>
</html>
I can't find what in your code is wrong, but I made some changes to it, and it worked. Here is the code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Scroll text box example</title>
<style>
#btn-up, #btn-down {
position: absolute;
top: 400px;
}
#btn-up {
left: 0px;
}
#btn-down {
left: 50px;
}
#btn-up, #btn-down {
width: 50px;
height: 50px;
background-color: yellow;
outline: 1px solid black;
}
#content-scroll-container {
position: absolute;
top: 0;
left: 0px;
width: 500px;
height: 250px; /* MASK HEIGHT real mask would be 200*/
overflow: hidden;
}
#content-scroll-inner {
position: absolute;
}
.cnt {
height: 100px;
width: 500px;
background-color: red;
}
.cnt:nth-child(even) {
height: 100px;
background-color: pink;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var scroller = {
config: {
curPos: 0, // position
el: 'content-scroll-container', // visible area (container)
elInner: 'content-scroll-inner', // inner content
cntPosY: null, // content top-left corner (0 position)
cntHeight: null, // content lenght
maskHeight: null, // visible area (rest is masked out)
animationSpeed: 500, // jquery animation speed, use 0 for no animation
isAnimationOn: false, // true when jquery is performing animation
},
data: '<div id="cnt-0" class="cnt">0</div><div id="cnt-1" class="cnt">1</div><div id="cnt-2" class="cnt">2</div><div id="cnt-3" class="cnt">3</div><div id="cnt-4" class="cnt">4</div><div id="cnt-5" class="cnt">5 empty</div>',
getCntPosition: function () {
// get y position of content
var elm = document.getElementById(this.config.elInner);
this.config.cntPosY = elm.offsetTop;
},
getCntSize: function () {
// get height for content
var elm = document.getElementById(this.config.elInner);
this.config.cntHeight = elm.clientHeight;
},
getMaskSize: function () {
// get height visible area
var elm = document.getElementById(this.config.el);
this.config.maskHeight = elm.clientHeight;
},
updateData: function () {
// refresh state
this.getMaskSize();
this.getCntPosition();
this.getCntSize();
//console.clear();
console.log(this.config);
},
logicShowHideArrows: function () {
if(this.config.curPos<1) {
$('#btn-up').hide();
} else {
$('#btn-up').show();
}
if(this.config.curPos>=4) {
$('#btn-down').hide();
} else {
$('#btn-down').show();
}
},
goUp: function () {
if(this.config.curPos<4 && scroller.config.isAnimationOn ==false) {
scroller.config.isAnimationOn = true;
scroller.config.curPos++;
if(scroller.config.curPos==1) {
$('#content-scroll-inner').animate({'top':'-=50px'},500,function(){
$('#cnt-'+scroller.config.curPos).animate({'height':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
this.config.incrementOf-=50;
$('#btn-up').show();
}
else {
$('#content-scroll-inner').animate({'top':'-=150px'},500,function(){
$('#cnt-'+scroller.config.curPos).animate({'height':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
this.config.incrementOf-=150;
}
this.updateData();
}
},
goDown: function () { //**************************
// user want to read next content
//this.updateData();
if(this.config.curPos>0 && scroller.config.isAnimationOn ==false) {
scroller.config.isAnimationOn = true;
if(this.config.curPos==1) {
$('#cnt-'+scroller.config.curPos).animate({'height':'-=50px'},500,function(){
$('#content-scroll-inner').animate({'top':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
scroller.config.curPos--;
this.config.incrementOf+=150;
this.updateData();
}
else {
$('#cnt-'+scroller.config.curPos).animate({'height':'-=50px'},500,function(){
$('#content-scroll-inner').animate({'top':'+=150px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
scroller.config.curPos--;
this.config.incrementOf+=150;
this.updateData();
}
}
},
setEventHandler: function () {
$('#btn-up').click(function() {
scroller.goDown();
});
$('#btn-down').click(function() {
scroller.goUp();
});
},
renderData: function () {
// render data content to slide
var elm = document.getElementById(this.config.elInner);
elm.innerHTML = this.data;
},
start: function () {
this.renderData();
this.updateData();
this.setEventHandler();
this.logicShowHideArrows();
}
};
</script>
</head>
<body onload="scroller.start();">
<div id="content-scroll-container">
<div id="content-scroll-inner">
</div>
</div>
<div id="btn-up">UP</div>
<div id="btn-down">DOWN</div>
</body>
</html>
I want to display my jQuery validation messages in a tooltip. In order to accomplish this, I started out by adding the following CSS rules to my stylesheet:
fieldset .field-validation-error {
display: none;
}
fieldset .field-validation-error.tooltip-icon {
background-image: url('/content/images/icons.png');
background-position: -32px -192px;
width: 16px;
height: 16px;
display: inline-block;
}
and a very small piece of JS code:
; (function ($) {
$(function() {
var fields = $("fieldset .field-validation-valid, fieldset .field-validation-error");
fields.each(function() {
var self = $(this);
self.addClass("tooltip-icon");
self.attr("rel", "tooltip");
self.attr("title", self.text());
self.text("");
self.tooltip();
});
});
})(jQuery);
The issue is that I now need to capture any event when the validation message changes, I've been looking at the source for jquery.validate.unobtrusive.js, and the method I'd need to hook to is the function onError(error, inputElement) method.
My tooltip plugin works as long as I've an updated title attribute, the issue comes when the field is revalidated, and the validation message is regenerated, I would need to hook into that and prevent the message from being put out there and place it in the title attribute instead.
I want to figure out a way to do this without modifying the actual jquery.validate.unobtrusive.js file.
On a second note, how could I improve this in order to leave the functionality unaltered in case javascript is disabled?
Ok I went with this, just in case anyone runs into this again:
; (function ($) {
$(function() {
function convertValidationMessagesToTooltips(form) {
var fields = $("fieldset .field-validation-valid, fieldset .field-validation-error", form);
fields.each(function() {
var self = $(this);
self.addClass("tooltip-icon");
self.attr("rel", "tooltip");
self.attr("title", self.text());
var span = self.find("span");
if (span.length) {
span.text("");
} else {
self.text("");
}
self.tooltip();
});
}
$("form").each(function() {
var form = $(this);
var settings = form.data("validator").settings;
var old_error_placement = settings.errorPlacement;
var new_error_placement = function() {
old_error_placement.apply(settings, arguments);
convertValidationMessagesToTooltips(form);
};
settings.errorPlacement = new_error_placement;
convertValidationMessagesToTooltips(form); // initialize in case of model-drawn validation messages at page render time.
});
});
})(jQuery);
and styles:
fieldset .field-validation-error { /* noscript */
display: block;
margin-bottom: 20px;
}
fieldset .field-validation-error.tooltip-icon { /* javascript enabled */
display: inline-block;
margin-bottom: 0px;
background-image: url('/content/images/icons.png');
background-position: -32px -192px;
width: 16px;
height: 16px;
vertical-align: middle;
}
I'll just include the tooltip script I have, since it's kind of custom-made (though I based it off someone else's).
; (function ($, window) {
$.fn.tooltip = function (){
var classes = {
tooltip: "tooltip",
top: "tooltip-top",
left: "tooltip-left",
right: "tooltip-right"
};
function init(self, tooltip) {
if ($(window).width() < tooltip.outerWidth() * 1.5) {
tooltip.css("max-width", $(window).width() / 2);
} else {
tooltip.css("max-width", 340);
}
var pos = {
x: self.offset().left + (self.outerWidth() / 2) - (tooltip.outerWidth() / 2),
y: self.offset().top - tooltip.outerHeight() - 20
};
if (pos.x < 0) {
pos.x = self.offset().left + self.outerWidth() / 2 - 20;
tooltip.addClass(classes.left);
} else {
tooltip.removeClass(classes.left);
}
if (pos.x + tooltip.outerWidth() > $(window).width()) {
pos.x = self.offset().left - tooltip.outerWidth() + self.outerWidth() / 2 + 20;
tooltip.addClass(classes.right);
} else {
tooltip.removeClass(classes.right);
}
if (pos.y < 0) {
pos.y = self.offset().top + self.outerHeight();
tooltip.addClass(classes.top);
} else {
tooltip.removeClass(classes.top);
}
tooltip.css({
left: pos.x,
top: pos.y
}).animate({
top: "+=10",
opacity: 1
}, 50);
};
function activate() {
var self = $(this);
var message = self.attr("title");
var tooltip = $("<div class='{0}'></div>".format(classes.tooltip));
if (!message) {
return;
}
self.removeAttr("title");
tooltip.css("opacity", 0).html(message).appendTo("body");
var reload = function() { // respec tooltip's size and position.
init(self, tooltip);
};
reload();
$(window).resize(reload);
var remove = function () {
tooltip.animate({
top: "-=10",
opacity: 0
}, 50, function() {
$(this).remove();
});
self.attr("title", message);
};
self.bind("mouseleave", remove);
tooltip.bind("click", remove);
};
return this.each(function () {
var self = $(this);
self.bind("mouseenter", activate);
});
};
$.tooltip = function() {
return $("[rel~=tooltip]").tooltip();
};
})(jQuery, window);
Consider the following example which should color every second row: (live demo here)
JS:
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
$("span").each(function(i) {
if (i % 10 >= 5) {
$(this).css("background-color", "red");
}
});
}
CSS:
div {
width: 450px;
height: 400px;
background-color: #ccc;
overflow: auto;
}
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #777;
margin: 0 30px 30px 0;
}
The output is:
As you can see, color_rows() function assumes that there are 5 elements per row. If, for example, I change the width of the div to be 350px, the color_rows() function will not work properly (i.e. will not color every second row).
How could I fix color_rows() so that it will work for every width of the div ?
this is my solution:
this works based on the top offset of each element and by comparing the it to the top offset of last element in the loop it detects if new row is seen or not, and then based on the number of row colors rows.
function color_rows() {
var lastTop = -1;
var rowCount = 0;
$("span").each(function(i) {
var top = $(this).position().top;
if (top != lastTop) {
rowCount++;
lastTop = top;
}
if(rowCount % 2 == 0)
{
$(this).css("background-color", "red");
}
});
}
jsFiddle: http://jsfiddle.net/Ug6wD/4/
Look at my fixes http://jsfiddle.net/Ug6wD/5/
I am getting Container width, itemWidth + margin. And calculating how many items per row. Get margin-right from span item.
Then minus 20 to the container width, coz of overflow scrollbar.
function color_rows() {
var containerWidth = $('div').width()-20;
var itemWidth = $('span:first').width() + parseInt($('span:first').css('margin-right'));
var itemsPerRow = parseInt(containerWidth / itemWidth);
$("span").each(function(i) {
if (i % (itemsPerRow *2) >= itemsPerRow ) {
$(this).css("background-color", "red");
}
});
}
UPDATE with dynamic margin-right value from CSS AND Right scrollbar fix causing breakage : http://jsfiddle.net/Ug6wD/5/
Edit: This only works on some div-widths.. -.- Nevermind, then..
This should do it:
function color_rows() {
var divW = $('div').width();
var spanW = $('span').outerWidth(true); //Get margin too
var cnt = parseInt(divW/spanW, 10); //Remove decimals
$("span").each(function(i) {
if (i % (cnt*2) >= cnt) {
$(this).css("background-color", "red");
}
});
}
fiddle: http://jsfiddle.net/gn5QW/1/
html
<div id="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
js
$(document).ready(function(){
var box = $(".box");
var con = $("#container");
var box_per_line = Math.floor(parseInt($("#container").width())/ (parseInt( $(".box").width()) +10*2/*px*/));
var style = "black";
$(".box").each(function(i){
if(i % box_per_line == 0){ style = (style == "black") ? "grey" : "black"; }
$(this).css("background-color",style);
});
});
css
.box {
width: 100px;
height: 100px;
float: left;
margin: 10px;
}
#conainer {
background-color: grey;
display: inline-block;
}
I've fixed your code, but please PLEASE don't do this. The internet the in pain,
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
var rowWidth = Number( $('div:first').css('width').slice(0,-2) );
var itemWidth = Number( $('span:first').css('width').slice(0,-2) ) + Number( $('span:first').css('margin-right').slice(0,-2) );
var perRow = Math.floor( rowWidth/itemWidth );
$("span").each(function(i) {
if (i % 10 >= perRow ) {
$(this).css("background-color", "red");
}
});
}
There is a simpler way:
$('tr:even').css("background-color", "red");