How can I make an interactive ticker? - javascript

I want to make a ticker that stops when user hovers over it and he can scroll up and down but I can't seem to find the way to make it so the user can freely scroll up and down so he can see all of the tickers unlike now that the user can only see the portion that is visible when he hovers codepen link: https://codepen.io/amin-rather/pen/ejJgZO
jQuery.fn.liScroll = function(settings) {
settings = jQuery.extend({
travelocity: 0.03
}, settings);
return this.each(function() {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripHeight = 1;
$strip.find("li").each(function(i) {
stripHeight += jQuery(this, i).outerHeight(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerHeight = $strip.parent().parent().height(); //a.k.a. 'mask' width
$strip.height(stripHeight);
var totalTravel = stripHeight;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({
top: '-=' + spazio
}, tempo, "linear", function() {
$strip.css("top", containerHeight);
scrollnews(totalTravel, defTiming);
});
}
scrollnews(totalTravel, defTiming);
$strip.hover(function() {
jQuery(this).stop();
},
function() {
var offset = jQuery(this).offset();
var residualSpace = offset.top + stripHeight;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});
};
$(function() {
$("ul#ticker01").liScroll();
});
.holder {
background - color: #bbdccb;
width: 300 px;
height: 250 px;
overflow: hidden;
padding: 10 px;
font - family: Helvetica;
}
.holder.mask {
position: relative;
left: 0 px;
top: 10 px;
width: 300 px;
height: 240 px;
overflow: hidden;
}
.holder ul {
list - style: none;
margin: 0;
padding: 0;
position: relative;
}
.holder ul li {
padding: 10 px 0 px;
}
.holder ul li a {
color: darkred;
text - decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="holder">
<ul id="ticker01">
<li><span>20/10/2018</span> T2 Exam of classes pre Nursery to 4th to start from 2/10/2018</li>
<li><span>15/07/2018</span> Student for INSPIRE AWARD to be nominated on 16th july</li>
<li><span>14/07/2018</span> School offers free admission for all classes</li>
<li><span>14/07/2018</span> Summer vacation to start from 19th july 2018</li>
<li><span>14/07/2018</span> Syllabus copies distributed among students</li>
<li><span>14/07/2018</span> Result of all classes will be announced after confirmation from higher authorities</li>
<li><span>14/07/2018</span> Normal class work resumed after T1 exam</li>
<li><span>14/07/2018</span> Uniform distributed among students</li>
</ul>
</div>

You can listen to the wheel event on the strip and adjust the offset according to the wheel delta.
To setup event listener with jQuery you can use the .on() function:
$strip.on('wheel', function (e) { // Attach listener to the wheel event on the $strip.
e.preventDefault(); // Disable default browser scrolling, when the user scroll over the $strip.
var offset = jQuery(this).offset(); // Get current offset of the $strip.
var delta = e.originalEvent.deltaY; // Get amount of the scroll.
// We can't use deltaY directly, as it's amount is not consistent between browsers, so:
var direction = Math.sign(delta); // Get direction of the scroll.
var sensitivity = 5; // You should adjust sensitivity for your needs.
offset.top += direction * sensitivity; // Calculate new top offset.
jQuery(this).offset(offset); // Set new offset to the $strip.
});
You should add it before the end of the .each() callback, so the full code is:
jQuery.fn.liScroll = function(settings) {
settings = jQuery.extend({
travelocity: 0.03
}, settings);
return this.each(function() {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripHeight = 1;
$strip.find("li").each(function(i) {
stripHeight += jQuery(this, i).outerHeight(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerHeight = $strip.parent().parent().height(); //a.k.a. 'mask' width
$strip.height(stripHeight);
var totalTravel = stripHeight;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({
top: '-=' + spazio
}, tempo, "linear", function() {
$strip.css("top", containerHeight);
scrollnews(totalTravel, defTiming);
});
}
scrollnews(totalTravel, defTiming);
$strip.hover(function() {
jQuery(this).stop();
},
function() {
var offset = jQuery(this).offset();
var residualSpace = offset.top + stripHeight;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
$strip.on('wheel', function (e) {
e.preventDefault();
var offset = jQuery(this).offset();
var delta = e.originalEvent.deltaY;
var direction = Math.sign(delta);
var sensitivity = 5;
offset.top += direction * sensitivity;
jQuery(this).offset(offset);
});
});
};
$(function() {
$("ul#ticker01").liScroll();
});

Related

How do you make JQuery WebTicket full-screen width?

Basically, the webticket only goes to about a little over 2/5ths of the screen, I'm trying to figure out how I can stretch the width out so that it covers the entire screen's width.
Fiddle: http://fiddle.jshell.net/Wf43X/56/light/
Javascript:
/*!
* webTicker 1.3
* Examples and documentation at:
* http://jonmifsud.com
* 2011 Jonathan Mifsud
* Version: 1.2 (26-JUNE-2011)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Requires:
* jQuery v1.4.2 or later
*
*/
(function($) {
var globalSettings = new Array();
var methods = {
init: function(settings) { // THIS
settings = jQuery.extend({
travelocity: 0.05,
direction: 1,
moving: true
}, settings);
globalSettings[jQuery(this).attr('id')] = settings;
return this.each(function() {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 0;
var $mask = $strip.wrap("<div class='mask'></div>");
$mask.after("<span class='tickeroverlay-left'> </span><span class='tickeroverlay-right'> </span>")
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
$strip.find("li").each(function(i) {
stripWidth += jQuery(this, i).outerWidth(true);
});
$strip.width(stripWidth + 200); //20 used for ie9 fix
function scrollnews(spazio, tempo) {
if (settings.direction == 1) $strip.animate({
left: '-=' + spazio
}, tempo, "linear", function() {
$strip.children().last().after($strip.children().first());
var first = $strip.children().first();
var width = first.outerWidth(true);
var defTiming = width / settings.travelocity;
//$strip.css("left", left);
$strip.css("left", '0');
scrollnews(width, defTiming);
});
else $strip.animate({
right: '-=' + spazio
}, tempo, "linear", function() {
$strip.children().last().after($strip.children().first());
var first = $strip.children().first();
var width = first.outerWidth(true);
var defTiming = width / settings.travelocity;
//$strip.css("left", left);
$strip.css("right", '0');
scrollnews(width, defTiming);
});
}
var first = $strip.children().first();
var travel = first.outerWidth(true);
var timing = travel / settings.travelocity;
scrollnews(travel, timing);
$strip.hover(function() {
jQuery(this).stop();
}, function() {
if (globalSettings[jQuery(this).attr('id')].moving) {
var offset = jQuery(this).offset();
var first = $strip.children().first();
var width = first.outerWidth(true);
var residualSpace;
if (settings.direction == 1) residualSpace = parseInt(jQuery(this).css('left').replace('px', '')) + width;
else residualSpace = parseInt(jQuery(this).css('right').replace('px', '')) + width;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
}
});
});
},
stop: function() {
if (globalSettings[jQuery(this).attr('id')].moving) {
globalSettings[jQuery(this).attr('id')].moving = false;
return this.each(function() {
jQuery(this).stop();
});
}
},
cont: function() { // GOOD
if (!(globalSettings[jQuery(this).attr('id')].moving)) {
globalSettings[jQuery(this).attr('id')].moving = true;
var settings = globalSettings[jQuery(this).attr('id')];
return this.each(function() {
var $strip = jQuery(this);
function scrollnews(spazio, tempo) {
if (settings.direction == 1) $strip.animate({
left: '-=' + spazio
}, tempo, "linear", function() {
$strip.children().last().after($strip.children().first());
var first = $strip.children().first();
var width = first.outerWidth(true);
var defTiming = width / settings.travelocity;
//$strip.css("left", left);
$strip.css("left", '0');
scrollnews(width, defTiming);
});
else $strip.animate({
right: '-=' + spazio
}, tempo, "linear", function() {
$strip.children().last().after($strip.children().first());
var first = $strip.children().first();
var width = first.outerWidth(true);
var defTiming = width / settings.travelocity;
//$strip.css("left", left);
$strip.css("right", '0');
scrollnews(width, defTiming);
});
}
var offset = jQuery(this).offset();
var first = $strip.children().first();
var width = first.outerWidth(true);
var residualSpace;
if (settings.direction == 1) residualSpace = parseInt(jQuery(this).css('left').replace('px', '')) + width;
else residualSpace = parseInt(jQuery(this).css('right').replace('px', '')) + width;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
}
}
};
$.fn.webTicker = function(method) {
// Method calling logic
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.webTicker');
}
};
})(jQuery);
jQuery('#webticker').webTicker()
CSS:
.tickercontainer { /* the outer div with the black border */
width: 500px;
height: 27px;
margin: 0;
padding: 0;
overflow: hidden;
}
.tickercontainer .mask { /* that serves as a mask. so you get a sort of padding both left and right */
position: relative;
top: 8px;
height: 18px;
/*width: 718px;*/
overflow: hidden;
}
ul.newsticker { /* that's your list */
position: relative;
/*left: 750px;*/
font: bold 10px Verdana;
list-style-type: none;
margin: 0;
padding: 0;
}
ul.newsticker li {
float: left; /* important: display inline gives incorrect results when you check for elem's width */
margin: 0;
padding-right: 15px;
/*background: #fff;*/
}
Thanks,
Dan

jquery plugin, settimeout and div not being append, simple weird case

I'm writing a jquery plugin the code below is not working (I mean the setTimeout is working but nothing is append)
var self = this;
for (var i=0; i<=10; i++) {
setTimeout(function() {
self.append(bubble);
}, 1000);
}
And the code below is working:
for (var i=0; i<=10; i++) {
this.append(bubble);
}
this is a jquery selection. I really don't get what's going on. It can't be scope issue .. can it be ? I don't get it. Thanks in advance for you help
Edit: bubble is a simple div (" ")
Below the whole plugin code:
(function($) {
'use strict';
$.fn.randomBubble = function(options) {
var self = this;
var settings = $.extend({
color: 'blue',
backgroundColor: 'white',
maxBubbleSize: 100
}, options);
var frame = {
height: this.height(),
width: this.width(),
}
var bubble = "<div class='randomBubble'> </div>";
this.getLeft = function(width) {
var left = Math.random() * frame.width;
if (left > (frame.width / 2)) {
left -= width;
} else {
left += width;
}
return left
}
this.getTop = function(height) {
var top = Math.random() * frame.height;
if (top > (frame.height / 2)) {
top -= height;
} else {
top += height;
}
return top
}
this.removeBubbles = function() {
var currentBubbles = this.find('.randomBubble');
if (currentBubbles.length) {
currentBubbles.remove();
}
}
window.oh = this;
for (var i = 0; i <= 10; i++) {
var timer = Math.random() * 1000;
setTimeout(function() {
window.uh = self;
self.append(bubble);
console.log("oh");
}, 1000);
}
this.randomize = function() {
//self.removeBubbles();
var allBubbles = this.find('.randomBubble');
allBubbles.each(function(i, el) {
var height = Math.random() * settings.maxBubbleSize;
var width = height;
$(el).css({
color: settings.color,
backgroundColor: settings.backgroundColor,
zIndex: 1000,
position: 'absolute',
borderRadius: '50%',
top: self.getTop(height),
left: self.getLeft(width),
height: height,
width: width
});
});
}
this.randomize();
//var run = setInterval(self.randomize, 4000);
return this.find('.randomBubble');
}
})(jQuery);
Because the bubbles are appended later due to the setTimeout(), this selector in your randomize() function comes up empty:
var allBubbles = this.find('.randomBubble');
That is why appending them in a simple for loop works fine.
If you really want to use the setTimout() to append your bubbles, one option is to style them when you add them:
setTimeout(function() {
var height = Math.random() * settings.maxBubbleSize;
var width = height;
var b = $(bubble).css({
color: settings.color,
backgroundColor: settings.backgroundColor,
zIndex: 1000,
position: 'absolute',
borderRadius: '50%',
top: self.getTop(height),
left: self.getLeft(width) ,
height: height,
width: width
});
self.append(b);
}, 1000);
Fiddle
Is it because you still call randomize() right away, even when you postpone the creation for one second?
You will also return an empty selection in that case, for the same reason.
Also, you probably want to use the timer variable in setTimeout() instead of hardcoding all to 1000 ms?
this is a javascript selection, the selector in jquery is $(this)
$.fn.randomBubble = function(options) {
var self = $(this);
};

How much of an element is visible in viewport

There's a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div might only partially show up or not at all.
What's the simplest algorithm to tell how much % of the div is visible in the viewport?
(To make things easier, the div always fits into the viewport horizontally, so only the Y axis needs to be considered at the calculations.)
See one more example in fiddle:
https://jsfiddle.net/1hfxom6h/3/
/*jslint browser: true*/
/*global jQuery, window, document*/
(function ($) {
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function (key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
var windowHeight = $(window).height(),
docScroll = $(document).scrollTop(),
divPosition = div$.offset().top,
divHeight = div$.height(),
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
function calculateAndDisplayForAllDivs() {
$('div').each(function () {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function () {
calculateAndDisplayForAllDivs();
});
$(document).ready(function () {
calculateAndDisplayForAllDivs();
});
}(jQuery));
div {
height:200px;
width:300px;
border-width:1px;
border-style:solid;
}
p {
position: fixed;
left:320px;
top:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>
Here's a snippet illustrating how you can calculate this.
I've put the % values in the boxes for readability, and it even kinda "follows" the viewport ^^ :
Fiddle version
function listVisibleBoxes() {
var results = [];
$("section").each(function () {
var screenTop = document.documentElement.scrollTop;
var screenBottom = document.documentElement.scrollTop + $(window).height();
var boxTop = $(this).offset().top;
var boxHeight = $(this).height();
var boxBottom = boxTop + boxHeight;
if(boxTop > screenTop) {
if(boxBottom < screenBottom) {
//full box
results.push(this.id + "-100%");
$(this).html("100%").css({ "line-height": "50vh" });
} else if(boxTop < screenBottom) {
//partial (bottom)
var percent = Math.round((screenBottom - boxTop) / boxHeight * 100) + "%";
var lineHeight = Math.round((screenBottom - boxTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
} else if(boxBottom > screenTop) {
//partial (top)
var percent = Math.round((boxBottom - screenTop) / boxHeight * 100) + "%";
var lineHeight = 100 - Math.round((boxBottom - screenTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
});
$("#data").html(results.join(" | "));
}
$(function () {
listVisibleBoxes();
$(window).on("scroll", function() {
listVisibleBoxes();
});
});
body {
background-color: rgba(255, 191, 127, 1);
font-family: Arial, sans-serif;
}
section {
background-color: rgba(175, 153, 131, 1);
height: 50vh;
font-size: 5vh;
line-height: 50vh;
margin: 10vh auto;
overflow: hidden;
text-align: center;
width: 50vw;
}
#data {
background-color: rgba(255, 255, 255, .5);
left: 0;
padding: .5em;
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="one"></section>
<section id="two"></section>
<section id="three"></section>
<section id="four"></section>
<section id="five"></section>
<section id="six"></section>
<div id="data">data here</div>
After playing around a bit I think I've found perhaps the simplest way to do it: I basically determine how much the element extends over the viewport (doesn't matter in which direction) and based on this it can easily be calculated how much of it is visible.
// When the page is completely loaded.
$(document).ready(function() {
// Returns in percentages how much can be seen vertically
// of an element in the current viewport.
$.fn.pvisible = function() {
var eTop = this.offset().top;
var eBottom = eTop + this.height();
var wTop = $(window).scrollTop();
var wBottom = wTop + $(window).height();
var totalH = Math.max(eBottom, wBottom) - Math.min(eTop, wTop);
var wComp = totalH - $(window).height();
var eIn = this.height() - wComp;
return (eIn <= 0 ? 0 : eIn / this.height() * 100);
}
// If the page is scrolled.
$(window).scroll(function() {
// Setting the opacity of the divs.
$("div").each(function() {
$(this).css("opacity", Math.round($(this).pvisible()) / 100);
});
});
});
html,
body {
width: 100%;
height: 100%;
}
body {
background-color: rgba(255, 191, 127, 1);
}
div {
width: 60%;
height: 30%;
margin: 5% auto;
background-color: rgba(175, 153, 131, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
A little illustration to help understand how it works:
Chrome now supports Intersection Observer API
Example (TypeScript):
export const elementVisibleInPercent = (element: HTMLElement) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
entries.forEach((entry: IntersectionObserverEntry) => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Example (JavaScript):
export const elementVisibleInPercent = (element) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Please note that the Intersection Observer API is available since then, made specifically for this purpose.

How to use % instead of px with draggable element?

I'm stucked and I need help. I'm making map with markers. I can add markers etc.
My main container have 100% width and height. When I click somewhere my marker has % values for example top: 34%; left: 35%;
After dragging marker new position have px value. I want to save % values.
Any ideas?
map.js
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
// $(maps).append('<div class="marker"></div>');
var marker = $('<div class="marker ui-widget-content"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker)
$('.marker').draggable().resizable();
}
map.click(function (e) {
// var x = e.pageX - this.offsetLeft;
// var y = e.pageY - this.offsetTop;
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
// $(this).append('<div class="marker"></div>');
AddPoint(x, y, this);
});
// drag function
$(".ui-widget-content").draggable({
drag: function( event, ui ) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
}
});
});
style.css
.wrapper {
margin: 0 auto;
width: 100%;
min-height: 400px;
overflow: hidden;
}
.map {
width: 100%;
position: relative;
}
.map > img {
max-width: 100%;
max-height: 100%;
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
position: absolute;
left: 50%;
top: 50%;
z-index: 999;
}
#mapa {
width: 30px;
height: 30px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
z-index: 999;
}
some html code
<div class="wrapper">
<div class="map">
<img src="http://i.imgur.com/HtxXGR5.jpg" width="100%" height="auto" margin="15px 0;" alt="">
</div>
<button id="remove">Remove all markers</button>
</div>
If you want to capture the position, after the drag is ended (fire 1 time per drag) you can do this:
$('.marker').draggable({
stop: function() {
var offset = $(this).offset();
var mapOffest = $('.map').offset();
var x = ((offset.left - mapOffest.left)/ ($(".map").width() / 100))+"%";
var y = ((offset.top - mapOffest.top)/ ($(".map").height() / 100))+"%";
// We need to do something with thoses vals uh?
$(this).css('left', x);
$(this).css('top', y);
// or
console.log('X:'+x + '||Y:'+y);
}
});
Fiddle here
Take note that the event has been set on the marker directy, this was probably your mistake.
The little calcul needs to take care of the map offset, which you don't need if your map is a full width/height (window size)
If you need, or prefer use the drag event rather than the stop, theses lines won't have any effects
$(this).css('left', x);
$(this).css('top', y);
But you'll still be able to capture the position, the console values will be goods.
Hope it may helps you.
problem solved, DFayet thank's again
final code
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
var marker = $('<div class="marker"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker);
$('.marker').draggable({
stop: function(event, ui) {
var thisNew = $(this);
var x = (ui.position.left / thisNew.parent().width()) * 100 + '%';
var y = (ui.position.top / thisNew.parent().height()) * 100 + '%';
thisNew.css('left', x);
thisNew.css('top', y);
console.log(x, y);
}
});
}
map.click(function (e) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
AddPoint(x, y, this);
});
});

JavaScript Div Expanding

I hope someone can help me with this.
When my HTML Textbox is clicked, I would like a Div to expand in length using preferably only JavaScript. I attached a picture to show in more depth. Again, If anyone could help me - I'll be greatfull.
Something like this should be sufficient, HTML:
<input type = "text" style = "width: 500px;" onfocus = "expand();" onblur = "collapse();">
<div id = "yourdiv"></div>
CSS:
#yourdiv {
margin-top: 0px;
background-color: rgb(0, 162, 232);
width: 500px;
height: 0px;
}
JavaScript:
var t;
function expand() {
var dv = document.getElementById("yourdiv");
var duration = 500; //number of milliseconds for animation; 1000ms = 1s.
var stepDur = Math.floor(duration / 200); //200px is our goal height here
var curHeight = parseInt(dv.style.height.substr(0, dv.style.height.length - 2), 10); //current height of dv
if(isNaN(curHeight)) {
curHeight = 0;
}
clearTimeout(t); //make sure no other animation is happening
function doAnim() {
if(curHeight >= 200) {
//we're done!
return;
}
curHeight ++;
dv.style.height = curHeight + "px";
t = setTimeout(doAnim, stepDur);
}
doAnim();
}
function collapse() {
var dv = document.getElementById("yourdiv");
var duration = 500; //number of milliseconds for animation; 1000ms = 1s.
var stepDur = Math.floor(duration / 200);
var curHeight = parseInt(dv.style.height.substr(0, dv.style.height.length - 2), 10); //current height of dv
clearTimeout(t); //make sure no other animation is happening
function doAnim() {
if(curHeight <= 0) {
//we're done!
return;
}
curHeight --;
dv.style.height = curHeight + "px";
t = setTimeout(doAnim, stepDur);
}
doAnim();
}
Demo: little link.
I hope that helped!

Categories