Change mousedown focus to a new div - javascript

So here's my code:
function drawGridSquare(tableText)
{
gridSquare = document.getElementById('square');
gridSquare.innerHTML = tableText;
document.body.appendChild(gridSquare);
gridSquare.style.display = 'block';
gridSquare.style.top = e.pageY - gridSquare.offsetHeight + 1;
gridSquare.style.left = e.pageX - gridSquare.offsetWidth/2;
gridSquare.focus();
}
This function is called on mousedown from a td element:
<td onmousedown="drawGridSquare('textData');">
This generates a pretty little square which uses jQuery draggable/droppable function. All I want to do is while the user's mouse is STILL pressed down, the focus would revert to the gridSquare that was created.
What are my options for this?

Seeing as how I couldn't find a clear way to do this, my work around is as follows:
function drawGridSquare(tableText, cellPosition)
{
gridSquare = document.getElementById('square');
gridSquare.innerHTML = tableText;
document.body.appendChild(gridSquare);
gridSquare.style.display = 'block';
startPositionX = endPositionX = cellPosition;
gridSquare.style.top = mouseY(event) - gridSquare.offsetHeight + 1;
gridSquare.style.left = mouseX(event) - gridSquare.offsetWidth/2;
squareReady = true;
}
function moveGridSquare()
{
if (squareReady)
{
squareIsMoving = true;
characterWidth = 1;
gridSquare = document.getElementById('square');
gridSquare.style.top = mouseY(event) - gridSquare.offsetHeight + 1;
gridSquare.style.left = mouseX(event) - gridSquare.offsetWidth/2;
}
}
function selectionEnd() {
if (squareIsMoving)
{
//Code to DROP INTO THE GRID
var dataStart = (Math.round((startPositionX) / characterWidth)) + 1;
var dataLength = Math.abs((Math.round((endPositionX)/characterWidth)) - (Math.round((startPositionX) / characterWidth)));
var data = dataStart + "," + dataLength + "," + theSelectedText;
dropDone(data);
//Set square to false
squareIsMoving = false;
squareReady=false;
//Destroy the square
document.getElementById('square').innerHTML = "";
document.getElementById('square').style.display = 'none';
}
}
<body onmousemove="moveGridSquare();">
<div id="square" onmousedown="squareReady=true;moveTheSquare();" onmouseup="selectionEnd();" style="display:none;" ></div>

Related

Tracking time and display it at next game

I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.

How to work mraid script into airpush

I have a query can you help me?I want to publish campaigns with mraid script into airpush and I have tested into mraid simulator (http://webtester.mraid.org/) its run perfectly on that.My script is:
<div id="adContainer" style="margin:0px;padding:0px;background-color:white;">
<div id="normal" style="display:none;margin:auto;position:relative;top:0px;left:0px;background-color:white;border-style:solid;border-width:1px;border-color:rgb(238,50,36);" onclick="javascript:resize();"><img id="smallbanner" style="position:relative!important;top:0px;left:0px;" src="http://winnowwin.com/ap/directory2422/21_banner.jpg" />
<a href="">
<div style="position:absolute;top:5px;right:5px;background-color:rgb(238,50,36);">
<div style="width:20px;height:20px;display:table-cell;text-align:center;vertical-align:middle;font-family: Arial, Helvetica, sans-serif;">X</div>
</div>
</a>
</div>
<div id="resized" style="display:none;margin:auto;position:relative;top:0px;left:0px;background-color:white;border-style:solid;border-width:1px;border-color:rgb(238,50,36);">
<img id="bigbanner" src="http://winnowwin.com/ap/directory2422/19_bg.png" />
<div style="position:absolute;top:5px;right:5px;background-color:rgb(238,50,36);">
<div style="width:20px;height:20px;display:table-cell;text-align:center;vertical-align:middle;font-family: Arial, Helvetica, sans-serif;">X</div>
</div>
</div>
</div>
<script>
function collapse() {
mraid.close();
}
function showMyAd() {
var el = document.getElementById("normal");
el.style.display = "";
mraid.addEventListener("stateChange", updateAd);
}
function resize() {
mraid.setResizeProperties({
"width": bw,
"height": bh,
"offsetX": 0,
"offsetY": 0,
"allowOffscreen": false
});
mraid.resize();
}
function updateAd(state) {
if (state == "resized") {
toggleLayer("normal", "resized");
} else if (state == "default") {
toggleLayer("resized", "normal");
}
}
function toggleLayer(fromLayer, toLayer) {
var fromElem = document.getElementById(fromLayer);
fromElem.style.display = "none";
var toElem = document.getElementById(toLayer);
toElem.style.display = "";
}
function doReadyCheck() {
var currentPosition = mraid.getCurrentPosition();
sw = currentPosition.width;
sh = currentPosition.height;
var adcon = document.getElementById("adContainer");
adcon.style.width = sw + "px";
var sb = document.getElementById("smallbanner");
sb.height = sh;
sb.width = sw;
var nor = document.getElementById("normal");
nor.style.width = parseInt(sw) - 2 + "px";
nor.style.height = parseInt(sh) - 2 + "px";
var maxSize = mraid.getMaxSize();
bw = maxSize.width;
bh = maxSize.height;
var bb = document.getElementById("bigbanner");
bb.height = bh;
bb.width = bw;
var e2 = document.getElementById("resized");
e2.style.width = bw + "px";
e2.style.height = bh + "px";
showMyAd();
}
var bw = "";
var bh = "";
var sw = "";
var sh = "";
doReadyCheck();
</script>
I'm facing issue, script is not rendering on airpush during published.can you tell me why it is happening?
You problem is you are directly using Mraid related functionality without waiting for mraid container to be in ready state. You need to wait until SDK/Container finishes initializing MRAID library into the webview, without doing will result your ad in bad/corrupt state because most of the mraid related methods will return wrong data or throw exceptions.
So you need to first wait until Mraid is in ready state and then add mraid related listeners or functionality
E.g.
function doReadyCheck()
{
if (mraid.getState() == 'loading')
{
mraid.addEventListener("ready", mraidIsReady);
}
else
{
mraidIsReady();
}
}
function mraidIsReady()
{
mraid.removeEventListener("ready", mraidIsReady);
//NOTE: Here you shall do rest of the stuff which you are currently doing in doReadyCheck method
var currentPosition = mraid.getCurrentPosition();
sw = currentPosition.width;
sh = currentPosition.height;
var adcon = document.getElementById("adContainer");
adcon.style.width = sw + "px";
var sb = document.getElementById("smallbanner");
sb.height = sh;
sb.width = sw;
var nor = document.getElementById("normal");
nor.style.width = parseInt(sw) - 2 + "px";
nor.style.height = parseInt(sh) - 2 + "px";
var maxSize = mraid.getMaxSize();
bw = maxSize.width;
bh = maxSize.height;
var bb = document.getElementById("bigbanner");
bb.height = bh;
bb.width = bw;
var e2 = document.getElementById("resized");
e2.style.width = bw + "px";
e2.style.height = bh + "px";
showMyAd();
}
doReadyCheck();

Having issues with live calculations, calculating each key stroke

I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.

How to make this ajax checker for multiple fields in the form?

I have the code below where it validates the form. How do i make it so i can reuse the code for other fields besides username?
How do i make it so i can have multiple other fields and use the same jquery code for validation?
<form name="form" id="form" class="form" action="success.html"
onsubmit="return validate(this)" method="post">
<label for="username">User Name:</label>
<input type="text" name="username" id="username" />
<label for="fullname">Full Name:</label>
<input type="text" name="fullname" id="fullname" />
<input type="submit" value="Submit" class="submit" />
</form>
And here is the jquery:
// form validation function //
function validate(form) {
var username = form.username.value;
var usernameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
if(username == "") {
inlineMsg('username','You must enter your username.',2);
return false;
}
if(!username.match(usernameRegex)) {
inlineMsg('username','You have entered an invalid username.',2);
return false;
}
if(username.length>20){
inlineMsg('username','Username is too long (max 20 char)', 2);
return false;
}
return true;
}
// START OF MESSAGE SCRIPT //
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
// build out the divs, set attributes and call the fade function
function inlineMsg(target,string,autohide) {
var msg;
var msgcontent;
if(!document.getElementById('msg')) {
msg = document.createElement('div');
msg.id = 'msg';
msgcontent = document.createElement('div');
msgcontent.id = 'msgcontent';
document.body.appendChild(msg);
msg.appendChild(msgcontent);
msg.style.filter = 'alpha(opacity=0)';
msg.style.opacity = 0;
msg.alpha = 0;
} else {
msg = document.getElementById('msg');
msgcontent = document.getElementById('msgcontent');
}
msgcontent.innerHTML = string;
msg.style.display = 'block';
var msgheight = msg.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
msg.style.top = topposition + 'px';
msg.style.left = leftposition + 'px';
clearInterval(msg.timer);
msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
if(!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
}
// hide the form alert //
function hideMsg(msg) {
var msg = document.getElementById('msg');
if(!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
}
// face the message box //
function fadeMsg(flag) {
if(flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if(flag == 1) {
value = msg.alpha + MSGSPEED;
} else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if(value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
} else if(value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
}
// calculate the position of the element in relation to the left
of the browser //
function leftPosition(target) {
var left = 0;
if(target.offsetParent) {
while(1) {
left += target.offsetLeft;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.x) {
left += target.x;
}
return left;
}
// calculate the position of the element in relation to the
top of the browser window //
function topPosition(target) {
var top = 0;
if(target.offsetParent) {
while(1) {
top += target.offsetTop;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.y) {
top += target.y;
}
return top;
}
// preload the arrow //
if(document.images) {
arrow = new Image(7,80);
arrow.src = "images/msg_arrow.gif";
}
Here is a plugin I used in the past:
https://github.com/posabsolute/jQuery-Validation-Engine
Take a look in there and it might be good for you. I personally modified it to fit my needs but that's a bit extreme.
You should never have to re-invent the wheel :)

How to dynamically add elements via jQuery

The script below creates a slider widget the takes a definition list and turns it into a slide deck. Each dt element is rotated via css to become the "spine", which is used to reveal that dt's sibling dd element.
What I'm trying to do is to enhance it so that I can have the option to remove the spines from the layout and just use forward and back buttons on either side of the slide deck. To do that, I set the dt's to display:none via CSS and use the code under the "Remove spine layout" comment to test for visible.
This works fine to remove the spines, now I need to dynamically create 2 absolutely positioned divs to hold the left and right arrow images, as well as attach a click handler to them.
My first problem is that my attempt to create the divs is not working.
Any help much appreciated.
jQuery.noConflict();
(function(jQuery) {
if (typeof jQuery == 'undefined') return;
jQuery.fn.easyAccordion = function(options) {
var defaults = {
slideNum: true,
autoStart: false,
pauseOnHover: true,
slideInterval: 5000
};
this.each(function() {
var settings = jQuery.extend(defaults, options);
jQuery(this).find('dl').addClass('easy-accordion');
// -------- Set the variables ------------------------------------------------------------------------------
jQuery.fn.setVariables = function() {
dlWidth = jQuery(this).width()-1;
dlHeight = jQuery(this).height();
if (!jQuery(this).find('dt').is(':visible')){
dtWidth = 0;
dtHeight = 0;
slideTotal = 0;
// Add an element to rewind to previous slide
var slidePrev = document.createElement('div');
slidePrev.className = 'slideAdv prev';
jQuery(this).append(slidePrev);
jQuery('.slideAdv.prev').css('background':'red','width':'50px','height':'50px');
// Add an element to advance to the next slide
var slideNext = document.createElement('div');
slideNext.className = 'slideAdv next';
jQuery(this).append(slideNext);
jQuery('.slideAdv.next').css('background':'green','width':'50px','height':'50px');
}
else
{
dtWidth = jQuery(this).find('dt').outerHeight();
if (jQuery.browser.msie){ dtWidth = jQuery(this).find('dt').outerWidth();}
dtHeight = dlHeight - (jQuery(this).find('dt').outerWidth()-jQuery(this).find('dt').width());
slideTotal = jQuery(this).find('dt').size();
}
ddWidth = dlWidth - (dtWidth*slideTotal) - (jQuery(this).find('dd').outerWidth(true)-jQuery(this).find('dd').width());
ddHeight = dlHeight - (jQuery(this).find('dd').outerHeight(true)-jQuery(this).find('dd').height());
};
jQuery(this).setVariables();
// -------- Fix some weird cross-browser issues due to the CSS rotation -------------------------------------
if (jQuery.browser.safari){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; /* Safari and Chrome */ }
if (jQuery.browser.mozilla){ var dtTop = dlHeight - 20; var dtOffset = - 20; /* FF */ }
if (jQuery.browser.msie){ var dtTop = 0; var dtOffset = 0; /* IE */ }
if (jQuery.browser.opera){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; } /* Opera */
// -------- Getting things ready ------------------------------------------------------------------------------
var f = 1;
var paused = false;
jQuery(this).find('dt').each(function(){
jQuery(this).css({'width':dtHeight,'top':dtTop,'margin-left':dtOffset});
// add unique id to each tab
jQuery(this).addClass('spine_' + f);
// add active corner
var corner = document.createElement('div');
corner.className = 'activeCorner spine_' + f;
jQuery(this).append(corner);
if(settings.slideNum == true){
jQuery('<span class="slide-number">'+f+'</span>').appendTo(this);
if(jQuery.browser.msie){
var slideNumLeft = parseInt(jQuery(this).find('.slide-number').css('left'));
if(jQuery.browser.version == 6.0 || jQuery.browser.version == 7.0){
jQuery(this).find('.slide-number').css({'bottom':'auto'});
slideNumLeft = slideNumLeft - 14;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
}
if(jQuery.browser.version == 8.0 || jQuery.browser.version == 9.0){
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top')) - 20;
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
slideNumLeft = slideNumLeft - 10;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
jQuery(this).find('.slide-number').css({'marginTop': 10});
}
} else {
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top'));
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
}
}
f = f + 1;
});
if(jQuery(this).find('.active').size()) {
jQuery(this).find('.active').next('dd').addClass('active');
} else {
jQuery(this).find('dt:first').addClass('active').next('dd').addClass('active');
}
jQuery(this).find('dt:first').css({'left':'0'}).next().css({'left':dtWidth});
jQuery(this).find('dd').css({'width':ddWidth,'height':ddHeight});
// -------- Functions ------------------------------------------------------------------------------
jQuery.fn.findActiveSlide = function() {
var i = 1;
this.find('dt').each(function(){
if(jQuery(this).hasClass('active')){
activeID = i; // Active slide
} else if (jQuery(this).hasClass('no-more-active')){
noMoreActiveID = i; // No more active slide
}
i = i + 1;
});
};
jQuery.fn.calculateSlidePos = function() {
var u = 2;
jQuery(this).find('dt').not(':first').each(function(){
var activeDtPos = dtWidth*activeID;
if(u <= activeID){
var leftDtPos = dtWidth*(u-1);
jQuery(this).animate({'left': leftDtPos});
if(u < activeID){ // If the item sits to the left of the active element
jQuery(this).next().css({'left':leftDtPos+dtWidth});
} else{ // If the item is the active one
jQuery(this).next().animate({'left':activeDtPos});
}
} else {
var rightDtPos = dlWidth-(dtWidth*(slideTotal-u+1));
jQuery(this).animate({'left': rightDtPos});
var rightDdPos = rightDtPos+dtWidth;
jQuery(this).next().animate({'left':rightDdPos});
}
u = u+ 1;
});
setTimeout( function() {
jQuery('.easy-accordion').find('dd').not('.active').each(function(){
jQuery(this).css({'display':'none'});
});
}, 400);
};
jQuery.fn.activateSlide = function() {
this.parent('dl').setVariables();
this.parent('dl').find('dd').css({'display':'block'});
this.parent('dl').find('dd.plus').removeClass('plus');
this.parent('dl').find('.no-more-active').removeClass('no-more-active');
this.parent('dl').find('.active').removeClass('active').addClass('no-more-active');
this.addClass('active').next().addClass('active');
this.parent('dl').findActiveSlide();
if(activeID < noMoreActiveID){
this.parent('dl').find('dd.no-more-active').addClass('plus');
}
this.parent('dl').calculateSlidePos();
};
jQuery.fn.rotateSlides = function(slideInterval, timerInstance) {
var accordianInstance = jQuery(this);
timerInstance.value = setTimeout(function(){accordianInstance.rotateSlides(slideInterval, timerInstance);}, slideInterval);
if (paused == false){
jQuery(this).findActiveSlide();
var totalSlides = jQuery(this).find('dt').size();
var activeSlide = activeID;
var newSlide = activeSlide + 1;
if (newSlide > totalSlides) {newSlide = 1; paused = true;}
jQuery(this).find('dt:eq(' + (newSlide-1) + ')').activateSlide(); // activate the new slide
}
}
// -------- Let's do it! ------------------------------------------------------------------------------
function trackerObject() {this.value = null}
var timerInstance = new trackerObject();
jQuery(this).findActiveSlide();
jQuery(this).calculateSlidePos();
if (settings.autoStart == true){
var accordianInstance = jQuery(this);
var interval = parseInt(settings.slideInterval);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
}
jQuery(this).find('dt').not('active').click(function(){
var accordianInstance = jQuery(this); //JSB to fix bug with IE < 9
jQuery(this).activateSlide();
clearTimeout(timerInstance.value);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
});
if (!(jQuery.browser.msie && jQuery.browser.version == 6.0)){
jQuery('dt').hover(function(){
jQuery(this).addClass('hover');
}, function(){
jQuery(this).removeClass('hover');
});
}
if (settings.pauseOnHover == true){
jQuery('dd').hover(function(){
paused = true;
}, function(){
paused = false;
});
}
});
};
})(jQuery);
Creating elements in jQuery is easy:
$newDiv = $('<div />');
$newDiv.css({
'position': 'absolute',
'top': '10px',
'left': '10px'
});
$newDiv.on('click', function() {
alert('You have clicked me');
});
$('#your_container').append($newDiv);

Categories