Jquery countdown timer that doesn't reset on page refresh - javascript

I need you help about this one. I am using Vassilis Dourdounis jquery plugin, and I have created countdown timer that hides some link on complete. But it restarts whenever the page is refreshed, and it shouldn't, it should finish the count and then disappear. Can anypne help, please?
This is jquery:
/*!
* jQuery Countdown plugin v1.0
* http://www.littlewebthings.com/projects/countdown/
*
* Copyright 2010, Vassilis Dourdounis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function($){
$.fn.countDown = function (options) {
config = {};
$.extend(config, options);
diffSecs = this.setCountDown(config);
if (config.onComplete)
{
$.data($(this)[0], 'callback', config.onComplete);
}
if (config.omitWeeks)
{
$.data($(this)[0], 'omitWeeks', config.omitWeeks);
}
$('#' + $(this).attr('id') + ' .digit').html('<div class="top"></div><div class="bottom"></div>');
$(this).doCountDown($(this).attr('id'), diffSecs, 500);
return this;
};
$.fn.stopCountDown = function () {
clearTimeout($.data(this[0], 'timer'));
};
$.fn.startCountDown = function () {
this.doCountDown($(this).attr('id'),$.data(this[0], 'diffSecs'), 500);
};
$.fn.setCountDown = function (options) {
var targetTime = new Date();
if (options.targetDate)
{
targetTime = new Date(options.targetDate.month + '/' + options.targetDate.day + '/' + options.targetDate.year + ' ' + options.targetDate.hour + ':' + options.targetDate.min + ':' + options.targetDate.sec + (options.targetDate.utc ? ' UTC' : ''));
}
else if (options.targetOffset)
{
targetTime.setFullYear(options.targetOffset.year + targetTime.getFullYear());
targetTime.setMonth(options.targetOffset.month + targetTime.getMonth());
targetTime.setDate(options.targetOffset.day + targetTime.getDate());
targetTime.setHours(options.targetOffset.hour + targetTime.getHours());
targetTime.setMinutes(options.targetOffset.min + targetTime.getMinutes());
targetTime.setSeconds(options.targetOffset.sec + targetTime.getSeconds());
}
var nowTime = new Date();
diffSecs = Math.floor((targetTime.valueOf()-nowTime.valueOf())/1000);
$.data(this[0], 'diffSecs', diffSecs);
return diffSecs;
};
$.fn.doCountDown = function (id, diffSecs, duration) {
$this = $('#' + id);
if (diffSecs <= 0)
{
diffSecs = 0;
if ($.data($this[0], 'timer'))
{
clearTimeout($.data($this[0], 'timer'));
}
}
secs = diffSecs % 60;
mins = Math.floor(diffSecs/60)%60;
hours = Math.floor(diffSecs/60/60)%24;
if ($.data($this[0], 'omitWeeks') == true)
{
days = Math.floor(diffSecs/60/60/24);
weeks = Math.floor(diffSecs/60/60/24/7);
}
else
{
days = Math.floor(diffSecs/60/60/24)%7;
weeks = Math.floor(diffSecs/60/60/24/7);
}
$this.dashChangeTo(id, 'seconds_dash', secs, duration ? duration : 800);
$this.dashChangeTo(id, 'minutes_dash', mins, duration ? duration : 1200);
$this.dashChangeTo(id, 'hours_dash', hours, duration ? duration : 1200);
$this.dashChangeTo(id, 'days_dash', days, duration ? duration : 1200);
$this.dashChangeTo(id, 'weeks_dash', weeks, duration ? duration : 1200);
$.data($this[0], 'diffSecs', diffSecs);
if (diffSecs > 0)
{
e = $this;
t = setTimeout(function() { e.doCountDown(id, diffSecs-1) } , 1000);
$.data(e[0], 'timer', t);
}
else if (cb = $.data($this[0], 'callback'))
{
$.data($this[0], 'callback')();
}
};
$.fn.dashChangeTo = function(id, dash, n, duration) {
$this = $('#' + id);
for (var i=($this.find('.' + dash + ' .digit').length-1); i>=0; i--)
{
var d = n%10;
n = (n - d) / 10;
$this.digitChangeTo('#' + $this.attr('id') + ' .' + dash + ' .digit:eq('+i+')', d, duration);
}
};
$.fn.digitChangeTo = function (digit, n, duration) {
if (!duration)
{
duration = 800;
}
if ($(digit + ' div.top').html() != n + '')
{
$(digit + ' div.top').css({'display': 'none'});
$(digit + ' div.top').html((n ? n : '0')).slideDown(duration);
$(digit + ' div.bottom').animate({'height': ''}, duration, function() {
$(digit + ' div.bottom').html($(digit + ' div.top').html());
$(digit + ' div.bottom').css({'display': 'block', 'height': ''});
$(digit + ' div.top').hide().slideUp(10);
});
}
};
})(jQuery);
This is HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script language="Javascript" type="text/javascript" src="js/jquery-1.4.1.js"></script>
<script language="Javascript" type="text/javascript" src="js/jquery.lwtCountdown-1.0.js"></script>
<script language="Javascript" type="text/javascript" src="js/jquery.cookie.js"></script>
<script language="Javascript" type="text/javascript" src="js/misc.js"></script>
<link rel="Stylesheet" type="text/css" href="style/main.css"></link>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test</title>
</head>
<body>
<div id="container">
<h2>OFFER</h2>
<img src="images/top.png" style="float:left;padding-left:15px;">
<div id="top_offer">
<p>REGISTER NOW AND GET SPECIAL BONUSES!</p>
</div>
<!-- Countdown dashboard start -->
<div id="countdown_dashboard">
<div class="dash minutes_dash">
<span class="dash_title"></span>
<div class="digit">0</div>
<div class="digit">0</div>
</div>
<div class="dash seconds_dash">
<span class="dash_title"></span>
<div class="digit">0</div>
<div class="digit">0</div>
</div>
</div>
<!-- Countdown dashboard end -->
<div class="info_message" id="complete_info_message">
<img src="images/offer.png" /> <p>Klikni ovde ► </p>
</div>
<script language="javascript" type="text/javascript">
// Set the Countdown
jQuery(document).ready(function() {
$('#countdown_dashboard').countDown({
targetOffset: {
'day': 0,
'month': 0,
'year': 0,
'hour': 0,
'min': 0,
'sec': 60
},
// onComplete function
onComplete: function() { $('#container').slideUp() }
});
});
</script>
</div>
</body>
</html>
THANK YOU!

are you sure this is called
$.cookie('mytimeout', count, {
expires: 7,
path: '/'
}
try putting it in the oncomplete function

Related

Changing the ref_id of a url to deliver tailor-made video content to users. Brightcove advanced embed code + Idomoo logic

Hello wise and helpful people of StackOverflow. I am using a combination of Brightcove as a video player and the sample code below is from a third-party company that I am supposed to use it with.
The main concept of what I am trying to achieve is the ability to deliver tailor-made video content to specific users by changing the ref_Id of the video on the URL. I have received sample code and instructions but I am still not sure how to go about this. I would very much appreciate all the help and insights I can get as I think this is a great project that's pretty cool in my opinion.
Basically I need to find out how to change the ref_Id of the URL so a different video can be played.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF8">
<!-- Bootstrap plugin & jquery plugin -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/bootstrap.js"></script>
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>-->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script><script type="text/javascript" src="jquery/js/jquery-3.2.0.min.js"></script>
<title>Landing-Page</title>
</head>
<body>
<div class="title">
<h1>LP Sample</h1>
</div>
<!-- video tag -->
<div class="video-container">
<video id="myPlayer"
crossorigin
data-account="5387496927001"
data-player="S1WpvbFwlW"
data-embed="default"
data-application-id
class="video-js" controls
autoplay
width="1280"
height="720">
</video>
<!--end video tag -->
<br/>
<!--link buttons-->
<div class="link">
<a id="movie2" href="javascript:" onclick="changeVideo()">Turn on audio description</a>
<a id="movie1" href="javascript:" onclick="openVideo()">Turn off audio description</a>
</div>
<!--end link buttons-->
<div class="button">
<button id="get-btn" type="button" class="btn btn-default">Click Here</button>
</div>
<!--player script-->
<script src="//players.brightcove.net/5387496927001/S1WpvbFwlW_default/index.min.js"></script>
</div>
</body>
<script>
/**
* the function gets the ID of the video from the url (the hashID is the refId of the video)
* */
function getParameterByName(hashId) {
var url = window.location.href;
hashId = hashId.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + hashId + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/**
* The Url query contain accountID/statsID/ClipID (have to be in this format)
* refId = all Url query
* hashOnly = ClipID
* */
var refId = getParameterByName('ref_id');
var params = refId.split("/");
var hashOnly = params[2];
var count = 0;
var myPlayer;
var srcPath;
var option;
var on;
var off;
var isOn = false;
var stats = "stats-usa.idomoo.com";
/**
* When the player load get the video object from the reference video 0000(have to set the ref video " 0000" in brightcove site)
* src value get the remote assets source we set in the brightcove site.
* the srcPth value get the path before the "0000/" (have to include the "0000/")
* finally the function set the new video in the player.
* */
videojs("myPlayer").ready(function () {
myPlayer = this;
//set video on start
myPlayer.catalog.getVideo("ref:0000", function (error, video) {
myPlayer.catalog.load(video);
//get path
var src = video.sources[0].src;
srcPath = src.substring(0, src.indexOf("0000/"));
myPlayer.mediainfo.name = "";
//set the poster img have to in the same path and same name
myPlayer.poster(srcPath + refId + ".jpg");
//diplay the CC button
myPlayer.mediainfo.textTracks = [
{
"src": srcPath + refId + "_en.vtt",
"srclang": "en",
"label": "en",
"kind": "captions",
"mime_type": "text/vtt"
}
];
option =
{
kind: "captions",
label: "EN",
language: "en",
src: srcPath + refId + "_en.vtt"
};
//Delete all the textTracks
var oldTracks = myPlayer.remoteTextTracks();
var i = oldTracks.length;
while (i--) {
myPlayer.removeRemoteTextTrack(oldTracks[i]);
}
;
//Add the caption object(option)
myPlayer.addRemoteTextTrack(option, true);
myPlayer.src({"type": "video/mp4", "src": srcPath + refId + ".mp4"});
myPlayer.play();
});
});
/**
* open video function --> loads the main video (without descriptive audio) to the player
*/
function openVideo() {
//remove older caption and set a new one
var oldTracks = myPlayer.remoteTextTracks();
var i = oldTracks.length;
while (i--) {
myPlayer.removeRemoteTextTrack(oldTracks[i]);
}
;
off =
{
kind: "captions",
label: "en",
language: "en",
src: srcPath + refId + "_en.vtt"
};
myPlayer.addRemoteTextTrack(off, true);
myPlayer.src({"type": "video/mp4", "src": srcPath + refId + ".mp4"});
myPlayer.play();
count = 0;
$("#movie1").hide();
$("#movie2").show();
isOn = false;
$("button.vjs-caption-toggle-control.vjs-icon-captions.vjs-control").removeClass("vjs-selected");
}
/**
* change video function --> loads the video with refID + "da"
* refID + "da" is the descriptive audio video version of the main audio
*/
function changeVideo() {
//remove older caption and set a new one
var oldTracks = myPlayer.remoteTextTracks();
var i = oldTracks.length;
while (i--) {
myPlayer.removeRemoteTextTrack(oldTracks[i]);
}
;
on =
{
kind: "captions",
label: "en",
language: "en",
src: srcPath + refId + "da_en.vtt"
};
myPlayer.addRemoteTextTrack(on, true);
myPlayer.src({"type": "video/mp4", "src": srcPath + refId + "da.mp4"});
myPlayer.play();
count = 0;
$("#movie2").hide();
$("#movie1").show();
isOn = true;
$("button.vjs-caption-toggle-control.vjs-icon-captions.vjs-control").removeClass("vjs-selected");
}
/**
* That function run until get the srcPath value from the video object from the brightcove
* and set it in href attribute in the transcript.
* the transcript html have to be in the same bucket and same name of the ClipID
*/
function waitForSrcPath() {
if (srcPath == null) {
setTimeout(waitForSrcPath, 50);
return;
}
}
var isFinished = false;
var stopInterval;
/**
* send Get request to idomoo analytics every 10 percent start at 0 until 100
*/
function analyticsVideoHandle() {
var currentTime = myPlayer.currentTime();
var videoTime = myPlayer.duration();
var timePercent = currentTime / videoTime;
var timeTemp = Math.ceil(timePercent * 10) * 10;
timeTemp = timeTemp - 10;
if (count != 0 && count <= timeTemp) {
count = timeTemp;
}
var rawTimeTemp = timePercent * 100;
rawTimeTemp = Math.floor(rawTimeTemp);
if (isOn) {
if (((Math.floor(rawTimeTemp) === timeTemp && count === timeTemp) || timePercent === 1) && !isFinished) {
if (timePercent != 1) {
count = count + 10;
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + 'da&atype=0&cvprogress=' + timeTemp,
'type': 'GET'
});
} else {
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + 'da&atype=0&cvprogress=' + 100,
'type': 'GET'
});
isFinished = true;
if (stop != null) {
clearInterval(stopInterval);
}
return;
}
}
} else {
if (((Math.floor(rawTimeTemp) === timeTemp && count === timeTemp) || timePercent === 1) && !isFinished) {
if (timePercent != 1) {
count = count + 10;
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + '&atype=0&cvprogress=' + timeTemp,
'type': 'GET'
});
} else {
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + '&atype=0&cvprogress=' + 100,
'type': 'GET'
});
isFinished = true;
if (stop != null) {
clearInterval(stopInterval);
}
return;
}
}
}
}
/**
* Send GET request to Idomoo analytics when the landing page load
*/
function analyticsOnLoad() {
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + '&atype=1&cfatype=1&landingPageVisited=' + window.location.href.split('?')[0],
'type': 'GET'
});
}
/**
* When click on the button "Click Here" send GET request to Idomoo analytics
*/
function analyticsOnClick() {
$("#get-btn").click(function () {
$.ajax({
'url': 'https://' + stats + '/?pid=' + params[0] + '&eiid=' + params[1] + '&eid=' + hashOnly + '&atype=1&cfatype=1&ccfan=CLICKHERE',
'type': 'GET'
});
});
}
/**
* Set to the player the attribute "data-customguid"
* run the function analyticsVideoHandle() every 50 milliseconds to check every change in video time until the video finish
*/
$(document).ready(function () {
waitForSrcPath();
$("#myPlayer").attr("data-customguid", "ref:" + refId);
analyticsOnLoad();
analyticsOnClick();
stopInterval = setInterval(function () {
analyticsVideoHandle();
}, 100);
});
</script>
</html>

Link in jQuery replaced HTML not working

I'm trying to make a simple plugin that collects the # of Facebook likes and tweets for a given URL (and let users tweet or like a given link). There is a total share count that expands to include LIs for likes and shares upon hover. Currently, on mouseover or select of the like/share LIs, the HTML of the Twitter/Facebook is replaced with a link and text with a subtle CTA. This link is supposed to open a new window with a share dialog for the given social site. However, this link doesn't seem to work at all.
HTML
<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div id="social">
<ul>
<li class="share">
<p>shares<p>
</li>
<li class="twitter"><p>tweets</p></li>
<li class="facebook"><p>likes</p></li>
</ul>
</div>
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/app.js"></scrpt>-->
</body>
</html>
jQuery
var fbCount,twCount,totalCount,
urlDebug = 'http://www.google.com',
urlCurrent = window.location.href,
twitterCountUrl = 'http://urls.api.twitter.com/1/urls/count.json?url=' + urlDebug + '&callback=?',
facebookCountUrl = 'https://graph.facebook.com/fql?q=SELECT%20share_count,%20like_count,%20comment_count,%20total_count,commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27' + urlDebug + '%27',
fbShareUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlDebug + "&t=" + document.title + 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600',
twShareUrl = "https://twitter.com/intent/tweet?text=" + document.title + "url=" + urlDebug;
$('.sharelink').on('click', function() {
window.open( $(this).attr('href') );
return false;
});
function getnumString(num) {
var numString;
if (num < 1000) {
numString = num;
} else if (num < 10000) {
// removed my rube goldberg contraption and lifted
// CMS version of this segment
numString = num.charAt(0) + ',' + num.substring(1);
} else if (num < 1000000) {
numString = (Math.round((num / 1000) * 10) / 10) + "k"
} else {
numString = (Math.round((num / 1000000) * 10) / 10) + "M"
}
return numString.toString();
}
$.when(
$.getJSON(twitterCountUrl, function twitterCount(data) {
twCount = data.count;
$('.twitter').append('<p class="num">' + getnumString(twCount) + '</p>');
}),
$.getJSON(facebookCountUrl,
function facebookCount(data) {
fbCount = data.data[0].like_count;
$('.facebook').append('<p class="num">' + getnumString(fbCount) + '</p>');
})).done(function(response) {
totalCount = fbCount + twCount;
$('.share').append('<p class="num">' + getnumString(totalCount) + '</p>');
});
$('#social ul').on('mouseover touchstart focusin', function() {
$('.facebook, .twitter').slideDown("slow");
}).on('mouseleave touchend focusout', function() {
$('.facebook, .twitter').hide();
});
$('#social .twitter').on('mouseenter focusin', function() {
$(this).html('TWEET<br>LINK');
$(this).children('a').addClass('sharelink');
}).on('mouseleave focusout', function() {
$(this).children('a').removeClass('sharelink');
$(this).html('<p> tweets</p>').append('<p class="num">' + getnumString(twCount) + '</p>');
});
$('#social .facebook').on('mouseenter focusin', function() {
$(this).html('SHARE<BR>ON FB');
$(this).children('a').addClass('sharelink');
}).on('mouseleave focusout', function() {
$(this).children('a').removeClass('sharelink');
$(this).html('<p>likes</p>').append('<p class="num">' + getnumString(fbCount) + '</p>');
});
When you add dynamic elements to DOM jQuery actually never cached that. You need to use delegated events so that when you add dynamic elements they are in scope and jQuery is listening
Case 1 (direct):
$("div#social .twitter").on("mouseenter focusin", function() {...});
== Hey! I want every span.twitter inside div#social to listen up: when you get mouseenter on, do X.
Case 2 (delegated):
$("div#social").on("mouseenter focusin", "span.twitter", function() {...});
== Hey, div#target! When any of your child elements which are "span.twitter" get mouseentered, do X with them.
Summary
In case 1, each of those spans has been individually given instructions. If new spans get created, they won't have heard the instruction and won't respond to clicks. Each span is directly responsible for its own events.
In case 2, only the container has been given the instruction; it is responsible for noticing clicks on behalf of its child elements. The work of catching events has been delegated.

JQuery Programmatically adding articles

I am trying to programmatically add articles to my website and then add a random word to each article using Jquery. I am able to make all the articles but I am not able to add text to the articles. Here is my code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js" type="text/javascript"></script>
<script src="Script/jquery.lorem.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var colors = ["#CCCCCC", "#333333", "#990099"];
var rand = Math.floor(Math.random() * colors.length);
$(function () {
for (var i = 0; i < Math.floor((Math.random() * 64) + 34) ; i++) {
$("#Inferface").append("<article class='box' style='background-color:" + colors[rand] + "'><span>" + i + "</span>");
}
});
// This line below should be adding the random word to each of the articles
$('.box').lorem({ type: 'words', amount: '1', ptags: false });
});
</script>
</head>
<body id="Inferface">
</body>
</html>
Strange, It seems to me that the code is working with very few adjustments
$(function ()
{
var colors = ["#CCCCCC", "#333333", "#990099"];
var rand = Math.floor(Math.random() * colors.length);
for (var i = 0; i < Math.floor((Math.random() * 64) + 34) ; i++)
{
$("#Interface").append("<article class='box' style='background-color:" + colors[rand] + "'><span>" + i + "</span>");
}
// This line below should be adding the random word to each of the articles
$('.box').lorem({ type: 'words', amount: '1', ptags: false});
});
.. you can check it out here :
Working Example

jQuery slider redirect the image

I'm using jQuery Blinds Slideshow as image slider. I want to redirect the first sliding image to http://google.com when I click on it. I use a html tag like this:
<div class="slideshow">
<ul>
<li><img src="lemons/1.jpg" alt="lemon" /></li>
<li><img src="lemons/2.jpg" alt="lemon tea" /></li>
</ul>
</div>
1
2
but it doesn't work.
My question is how can I redirect the first sliding image to google.com when I click on it ?
Thanks in advance.
Here is something quick and dirty I cooked up modifying the original jquery-blinds.
Put it in a new JS file and call it jquery.blinds-0.9-with-hyperlinks.js or something and include it in place of the current jquery-blinds code.
It should work with the HTML you posted above. It simply checks if any of the images are wrapped in an '' tag and if it is, makes the image redirect to that link on click.
/*!
* jQuery Blinds
* http://www.littlewebthings.com/projects/blinds
*
* Copyright 2010, Vassilis Dourdounis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Modified by Thomas Antony ( http://www.thomasantony.net ) on 06-Apr-2012
* Added image hyperlinking functionality
*
*/
(function($){
$.fn.blinds = function (options) {
$(this).find('li').hide();
$(this).addClass('blinds_slideshow');
settings = {};
settings.tile_orchestration = this.tile_orchestration;
settings.h_res = 12;
settings.v_res = 1;
settings.width = $(this).find('li:first').width();
settings.height = $(this).find('li:first').height();
jQuery.extend(settings, options);
tiles_width = settings.width / settings.h_res;
tiles_height = settings.height / settings.v_res;
// Get image list
blinds_images = [];
blinds_links = [];
$(this).find('img').each(function (i, e) {
blinds_images[blinds_images.length] = {'title': e.alt, 'src': e.src}
// Code added to allow for linking functionality -- Thomas
if( $(e).parent().is('a') && $(e).parent().attr('href') != undefined)
{
blinds_links[i] = $(e).parent().attr('href');
}else{
blinds_links[i] = "";
}
});
// Create blinds_container
$(this).append('<div class="blinds_container"></div>');
blinds_container = $(this).find('.blinds_container');
blinds_container.css({
'position' : 'relative',
'display' : 'block',
'width' : settings.width,
'height' : settings.height,
// 'border' : '1px solid red', // debuging
'background': 'transparent url("' + blinds_images[1]['src'] + '") 0px 0px no-repeat'
} );
// Setup tiles
for (i = 0; i < settings.h_res; i++)
{
for (j = 0; j < settings.v_res; j++)
{
if (tile = $(this).find('.tile_' + i + '_' + j))
{
h = '<div class="outer_tile_' + i + '_' + j + '"><div class="tile_' + i + '_' + j + '"></div></div>';
blinds_container.append(h);
outer_tile = $(this).find('.outer_tile_' + i + '_' + j);
outer_tile.css({
'position' : 'absolute',
'width' : tiles_width,
'height' : tiles_height,
'left' : i * tiles_width,
'top' : j * tiles_height
})
tile = $(this).find('.tile_' + i + '_' + j);
tile.css({
'position' : 'absolute',
'width' : tiles_width,
'height' : tiles_height,
'left' : 0,
'top' : 0,
// 'border' : '1px solid red', // debuging
'background': 'transparent url("' + blinds_images[0]['src'] + '") -' + (i * tiles_width) + 'px -' + (j * tiles_height) + 'px no-repeat'
})
jQuery.data($(tile)[0], 'blinds_position', {'i': i, 'j': j});
}
}
}
jQuery.data(this[0], 'blinds_config', {
'h_res': settings.h_res,
'v_res': settings.v_res,
'tiles_width': tiles_width,
'tiles_height': tiles_height,
'images': blinds_images,
'img_index': 0,
'change_buffer': 0,
'tile_orchestration': settings.tile_orchestration
});
// Add redirection code for the links -- Thomas
var container = this[0]; // Need this to get config data within click handler
jQuery.data(this[0], 'blinds_links', blinds_links);
blinds_container.click(function(){
var config = jQuery.data(container, 'blinds_config');
if(blinds_links[config.img_index] != "")
{
window.location.href = blinds_links[config.img_index]
}
});
$(this).update_cursor(); // Set correct cursor for first image -- Thomas
// Modified code ends
}
$.fn.blinds_change = function (img_index) {
// reset all sprites
config = jQuery.data($(this)[0], 'blinds_config');
for (i = 0; i < config.h_res; i++)
{
for (j = 0; j < config.v_res; j++) {
$(this).find('.tile_' + i + '_' + j).show().css('background', 'transparent ' + 'url("' + config.images[config.img_index]['src'] + '") -' + (i * config.tiles_width) + 'px -' + (j * config.tiles_height) + 'px no-repeat');
}
}
$(this).children('.blinds_container').css('background', 'transparent url("' + blinds_images[img_index]['src'] + '") 0px 0px no-repeat' );
config.img_index = img_index;
jQuery.data($(this)[0], 'blinds_config', config);
for (i = 0; i < config.h_res; i++)
{
for (j = 0; j < config.v_res; j++) {
t = config.tile_orchestration(i, j, config.h_res, config.v_res);
config = jQuery.data($(this)[0], 'blinds_config');
config.change_buffer = config.change_buffer + 1;
jQuery.data(this[0], 'blinds_config', config);
$(this).find('.tile_' + i + '_' + j).fadeOut(t, function() {
blinds_pos = jQuery.data($(this)[0], 'blinds_position');
config = jQuery.data($(this).parents('.blinds_slideshow')[0], 'blinds_config');
$(this).css('background', 'transparent ' + 'url("' + config.images[config.img_index]['src'] + '") -' + (blinds_pos.i * config.tiles_width) + 'px -' + (blinds_pos.j * config.tiles_height) + 'px no-repeat');
config.change_buffer = config.change_buffer - 1;
jQuery.data($(this).parents('.blinds_slideshow')[0], 'blinds_config', config);
if (config.change_buffer == 0) {
// $(this).parent().parent().children().children().css('width', config.tiles_width);
$(this).parent().parent().children().children().show();
}
});
}
}
$(this).update_cursor();
}
$.fn.tile_orchestration = function (i, j, total_x, total_y) {
return (Math.abs(i-total_x/2)+Math.abs(j-total_y/2))*100;
}
// Function to update cursor to a "hand" if image is linked -- Thomas
$.fn.update_cursor = function()
{
// Change cursor if image is hyperlinked
var config = jQuery.data($(this)[0], 'blinds_config');
var blinds_links = jQuery.data($(this)[0], 'blinds_links'); // get links from saved data
console.log(config.img_index);
if(blinds_links[config.img_index] != "")
{
$(this).find('.blinds_container').css('cursor','pointer');
}else{
$(this).find('.blinds_container').css('cursor','auto');
}
}
})(jQuery);
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('a:first').click(function(){
window.location.href = 'http://google.com/';
});
});
</script>
Or
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('div.slideshow img:first').click(function(){
window.location.href = 'http://google.com/';
});
});

Button for continous scrolling of a div with Javascript code

Found this code on the net. Want to modify it to make it scroll a div continously when the mouse button is down and stop scrolling when the mouse button is up. I tried this:
Change from the click event to the mousedown event. That did not do it.
Added a call to the same function within the function. That did not do it either.
What should I modify in this function to have the continous scrolling on mouse down?
(function ($) {
var vscrollid = 0;
$.fn.vScroll = function (options) {
var options = $.extend({}, { speed: 500, height: 300, upID: "#up-arrow", downID: "#bottom-arrow", cycle: true }, options);
return this.each(function () {
vscrollid++;
obj = $(this);
var newid = vscrollid;
obj.css("overflow", "hidden");
obj.css("position", "relative");
obj.css("height", options.height + "px");
obj.children().each(
function (intIndex) {
$(this).addClass("vscroll-" + vscrollid + "-" + intIndex);
});
var itemCount = 0;
$(options.downID).click(function () {
var nextCount = itemCount + 1;
if ($('.vscroll-' + newid + '-' + nextCount).length) {
var divH = $('.vscroll-' + newid + '-' + itemCount).outerHeight();
itemCount++;
$("#vscroller-" + newid).animate({
top: "-=" + divH + "px"
}, options.speed);
}
else {
if (options.cycle) {
itemCount = 0;
$("#vscroller-" + newid).animate({
top: "0" + "px"
}, options.speed);
}
}
});
$(options.upID).click(function () {
var prevCount = itemCount - 1;
if ($('.vscroll-' + newid + '-' + prevCount).length) {
itemCount--;
var divH = $('.vscroll-' + newid + '-' + itemCount).outerHeight();
$("#vscroller-" + newid).animate({
top: "+=" + divH + "px"
}, options.speed);
}
});
obj.children().wrapAll("<div style='position: relative; top: 0' id='vscroller-" + vscrollid + "'></div>");
});
};
})(jQuery);
/*
* jQuery vScroll
* Copyright (c) 2011 Simon Hibbard
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* Version: V1.2.0
* Release: 10-02-2011
* Based on jQuery 1.4.2
*/
Was able to get the continuous scrolling with simpler code.
<script type="text/javascript">
$(document).ready(function($) {
$(".scrolling_prev", $("#'.$node['ID'].'")).mousedown(function() {
startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "-=50px");
}).mouseup(function() {
$(".link_drop_box", $("#'.$node['ID'].'")).stop()
});
$(".scrolling_next", $("#'.$node['ID'].'")).mousedown(function() {
startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "+=50px");
}).mouseup(function() {
$(".link_drop_box", $("#'.$node['ID'].'")).stop();
});
});
</script>

Categories