So I have a div duplication function for when a user wants to add a speaker, and a function for deleting one of said speakers.
In the latter function, in the event that all the speakers have been removed, I want to reveal the only remaining div of class speaker (the ID doesn't matter).
My function for switching between speakers (bottom) works fine (.hide()), but not the removal function. Heck even when I take out the if statement it doesn't work. Please assist!
$('#submitSpeaker').click(
function duplicateSpeaker() {
var original = $('#speaker' + speakerCount);
var clone = original.clone(true, true);
var textnode = original.find('.speakerName').val();
var node = document.createElement("LI");
var a = document.createElement("a");
if (textnode == '') {
$.Dialog({
title: 'Wizard',
flat: true,
content: 'You must enter a Speaker Name.',
shadow: true,
padding: 10
});
return;
}
node.setAttribute('class', 'active speakerLI');
node.setAttribute('id', 'speakerLI' + speakerCount)
clone.attr("id", "speaker" + ++speakerCount);
original.hide();
original.parent().append(clone);
a.setAttribute('class', 'gotoSpeaker');
$(node).append(a);
$(a).append(textnode + ' ' + "<i class='icon-minus removeSpeaker'></i>");
document.getElementById("speakerList").appendChild(node);
clone.find('input').val('').end();
clone.find('textarea').val('').end();
clone.find('img').attr('src', '#');
});
$("#speakerList").on("click", "i.removeSpeaker", function () {
var speakerNum = $(this).closest('li').attr('id').replace(/speakerLI/, '');
$('#speaker' + speakerNum).remove();
$(this).closest('li').remove();
if ($('.speaker').length == 1) {
$('.speaker').show();
};
});
$("#speakerList").on("click", "a.gotoSpeaker", function () {
var speakerNum = $(this).closest('li').attr('id').replace(/speakerLI/, '');
$(".speaker").hide();
$('#speaker' + speakerNum).show();
});
Related
I'm working on implementing a system where elements can be dragged and dropped to create flowcharts. My Issue is with saving the flowchart so that it could be reloaded when needed. For now I've created a method that saves all the previous data of the element onto the final array that holds only elements that are dropped on the container. But I'm getting a Trivial Error as Undefined variable on the debugging interface. Hence I'm not getting the intended output and the alert messages that I included are not being printed when the condition is met.
Code in Context
function saveFlowchart()
{
var nodes = [];
var matches = [];
var searchEles = document.getElementById("container").children;
for(var i = 0; i < searchEles.length; i++)
{
matches.push(searchEles[i]);
var idOfEl = searchEles[i].id;
if(searchEles[i].id !=null || searchEles[i].id !="")
{
var $element = $("#" + searchEles[i].id);
var dropElem = $("#" + searchEles[i].id).attr('class');
var position = $element.position();
position.bottom = position.top + $element.height();
position.right = position.left + $element.width();
alert("class:"+dropElem+"\nTop position: " + position.top + "\nLeft position: " + position.left + "\nBottom position: " + position.bottom + "\nRight position: " + position.right);
finalArray[idOfEl-1][0]= idOfEl;
finalArray[idOfEl-1][1]= dropElem;
var elId = parseInt(idOfEl);
if (dropElem == "stream ui-draggable")
{
for(var count=0;count<100;count++)
{
alert("One loop opened with count="+count);
if(createdImportStreamArray[count][0]==elId)
{
finalArray[elId-1][2]= createdImportStreamArray[count][1]; //Selected Stream from Predefined Streams
finalArray[elId-1][3]= createdImportStreamArray[count][2]; //asName
alert("createdImportStreamArray[count][0]==elId");
}
else if(createdExportStreamArray[count][0]==elId)
{
finalArray[elId-1][2]= createdExportStreamArray[count][1]; //Selected Stream from Predefined Streams
finalArray[elId-1][3]= createdExportStreamArray[count][2]; //asName
}
else if(createdDefinedStreamArray[count][0]==elId)
{
finalArray[elId-1][2]= createdDefinedStreamArray[count][1]; //Stream Name
finalArray[elId-1][3]= createdDefinedStreamArray[count][4]; //Number of Attributes
finalArray[elId-1][4]=[];
for(var f=0;f<createdDefinedStreamArray[r][4];f++)
{
finalArray[elId-1][4][f][0]=createdDefinedStreamArray[count][2][f][0]; //Attribute Name
finalArray[elId-1][4][f][1]=createdDefinedStreamArray[count][2][f][1]; // Attribute Type
}
}
alert("One loop closed with count="+count);
}
alert("Loop ended with count="+count);
}
else if (dropElem == "wstream ui-draggable")
{
ElementType="wstream";
}
// else if conditions...
alert(finalArray);
}
}
//Code to output the connection details in a json format
//The following is not affected by the above mentioned error
$(".node").each(function (idx, elem) {
var $elem = $(elem);
var endpoints = jsPlumb.getEndpoints($elem.attr('id'));
console.log('endpoints of '+$elem.attr('id'));
console.log(endpoints);
nodes.push({
blockId: $elem.attr('id'),
nodetype: $elem.attr('data-nodetype'),
positionX: parseInt($elem.css("left"), 10),
positionY: parseInt($elem.css("top"), 10)
});
});
var connections = [];
$.each(jsPlumb.getConnections(), function (idx, connection) {
connections.push({
connectionId: connection.id,
pageSourceId: connection.sourceId,
pageTargetId: connection.targetId
});
});
var flowChart = {};
flowChart.nodes = nodes;
flowChart.connections = connections;
flowChart.numberOfElements = numberOfElements;
var flowChartJson = JSON.stringify(flowChart);
//console.log(flowChartJson);
$('#jsonOutput').val(flowChartJson);
}
Debugging Interface
According to this the count variable in the for loop is undefined. I've tried taking the first statement var count=0 outside the loop declaration part and defining it in the very beginning of the method. But that simply checks for count=0 against the conditions and doesn't increment at all.
Any help in this regard will be highly appreciated as I've been working on this minor error for almost 2 days now.
I've the following code:
this.showNotificationcenter = function () {
centerNotification =
$("<div class='notificationbar'> <h2>Notificaties</h2>" +
"<ul></ul></div>");
var fullPage = $(document).find("#fullPage");
fullPage.append(centerNotification);
}
this.center = function (options) {
var notificationsUl = $(centerNotification).find("ul");
notification = $("<li id="+options.id+"><b>" + options.title + "<span class='fa fa-times'></span></b><br />" + options.content + "</li>");
notificationsUl.append(notification);
}
this.removeLi = function () {
var test = $(notification).find("id").val();
}
And I use this code to create a notification:
eformity.notification.center({
title: "Dit is een titel",
content: "Dit is een content",
id: "een",
});
I need to get the options.id in the function removeLi but I've no idea how to. (var test is now undefined) Eventually, I need a click event on the span which will delete that Li. Can someone help me? Thanks in advance.
you should be using attr to find the value of the attribute id.
var test = $(notification).attr("id");
To get Id
var test=$(notification).attr('id');
To replace Id
var test=$(notification).attr('id', 'newId');
I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.
Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});
Do you write
$(Document)
Instead of $(document) with small letter "d".
How can I insert text/code at the cursors place in a div created by NicEdit?
I've tried to read the documentation and create my own plugin, but I want it to work without the tool bar (Modal Window)
This is a quick solution and tested in firefox only. But it works and should be adaptable for IE and other browsers.
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}
Insert Html Plugin
Don't know if this will help or not, but this is the plugin I created for inserting Html at the cursor position. The button opens a content pane and I just paste in the html I want and submit. Works for me!
var nicMyhtmlOptions = {
buttons : {
'html' : {name : 'Insert Html', type : 'nicMyhtmlButton'}
},iconFiles : {'html' : '/nicedit/html_add.gif'}
};
var nicMyhtmlButton=nicEditorAdvancedButton.extend({
addPane: function () {
this.addForm({
'': { type: 'title', txt: 'Insert Html' },
'code' : {type : 'content', 'value' : '', style : {width: '340px', height : '200px'}}
});
},
submit : function(e) {
var mycode = this.inputs['code'].value;
this.removePane();
this.ne.nicCommand('insertHTML', mycode );
}
});
nicEditors.registerPlugin(nicPlugin,nicMyhtmlOptions);
I used the html_add icon from Silk Icons, pasted onto a transparent 18 x 18 and saved as gif in the same folder as nicEditorIcons.gif.
It works for me when I use:
function neInsertHTML(value){
$('.nicEdit-main').focus(); // Without focus it wont work!
// Inserts into first instance, you can replace it by nicEditors.findEditor('ID');
myNicEditor.nicInstances[0].nicCommand('InsertHTML', value);
}
The way I solved this was to make the nicEdit Instance div droppable, using jQuery UI; but to also make all of the elements within the div droppable.
$('div.nicEdit-main').droppable({
activeClass: 'dropReady',
hoverClass: 'dropPending',
drop: function(event,ui) {
$(this).find('.cursor').removeClass('cursor');
},
over: function(event, ui) {
if($(this).find('.cursor').length == 0) {
var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
$(this).append(insertEl);
}
},
out: function(event, ui) {
$(this).find('.cursor').remove();
},
greedy: true
});
$('div.nicEdit-main').find('*').droppable({
activeClass: 'dropReady',
hoverClass: 'dropPending',
drop: function(event,ui) {
$(this).find('.cursor').removeClass('cursor');
},
over: function(event, ui) {
var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
$(this).append(insertEl);
},
out: function(event, ui) {
$(this).find('.cursor').remove();
},
greedy: true
});
Then make your code or text draggable:
$('.field').draggable({
appendTo: '.content', //This is just a higher level DOM element
revert: true,
cursor: 'pointer',
zIndex: 1500, // Make sure draggable drags above everything else
containment: 'DOM',
helper: 'clone' //Clone it while dragging (keep original intact)
});
Then finally make sure you set the value of the draggable element to what you want to insert, and/or modify the code below to insert the element (span) of your choice.
$sHTML .= "<div class='field' value='{{".$config[0]."}}'>".$config[1]."</div>";
A response to #Reto: This code works, I just needed to add some fix because it doesn't insert anything if text area is empty. Also it adds only plain text. Here is the code if anybody need it:
if(editorField.nodeValue==null){
editor.setContent('<strong>Your content</strong>');
}else{
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
'<strong>Your content</strong>' +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
editor.setContent(editorField.nodeValue);
}
Change follwoing in NicEdit.js File
Updated from Reto Aebersold Ans It will handle Null Node exception, if text area is empty
update: function (A) {
(this.options.command);
if (this.options.command == 'InsertBookmark') {
var editor = nicEditors.findEditor("cpMain_area2");
var range = editor.getRng();
var editorField = editor.selElm();
// alert(editorField.content);
if (editorField.nodeValue == null) {
// editorField.setContent('"' + A + '"')
var oldStr = A.replace("<<", "").replace(">>", "");
editorField.setContent("<<" + oldStr + ">>");
}
else {
// alert('Not Null');
// alert(editorField.nodeValue + ' ' + A);
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) + A + editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}
}
else {
// alert(A);
/* END HERE */
this.ne.nicCommand(this.options.command, A);
}
This function work when nicEdit textarea is empty or cursor is in the blank or new line.
function addToCursorPosition(textareaId,value) {
var editor = nicEditors.findEditor(textareaId);
var range = editor.getRng();
var editorField = editor.selElm();
var start = range.startOffset;
var end = range.endOffset;
if (editorField.nodeValue != null) {
editorField.nodeValue = editorField.nodeValue.substring(0, start) +
value +
editorField.nodeValue.substring(end, editorField.nodeValue.length);
}
else {
var content = nicEditors.findEditor(textareaId).getContent().split("<br>");
var linesCount = 0;
var before = "";
var after = "";
for (var i = 0; i < content.length; i++) {
if (linesCount < start) {
before += content[i] + "<br>";
}
else {
after += content[i] + "<br>";
}
linesCount++;
if (content[i]!="") {
linesCount++;
}
}
nicEditors.findEditor(textareaId).setContent(before + value + after);
}
}
I have quickly coded up a sort of product display thing that gets half of its input from the page, and the other half from an AJAX query.
Here is the code...
function productDisplay() {
products = [];
this.index = 0;
setupProductDisplay();
processListItems();
showProduct();
function setupProductDisplay() {
var productInfoBoxHtml = '<div id="product-info"><h3 class="hide-me"></h3><span id="dimensions" class="hide-me"></span><div id="product-gallery"><img alt="" src="" /></div><ul id="product-options" class="hide-me"><li id="spex-sheet">Download full spex sheet</li><li id="enlarge-image">Enlarge image</li></ul><div id="product-description" class="hide-me"></div><span id="top"></span><span id="bottom"></span><span id="side"></span><span class="loading"></span></div>';
$('#products').after(productInfoBoxHtml);
}
function processListItems() {
$('#products > li')
.append('<span class="product-view">View</span>')
.filter(':even')
.addClass('even')
.end()
.each(function() {
products.push({
id: $(this).find('h3').html(),
title: $(this).find('h3').html(),
dimensions: $(this).find('.dimensions').html(),
description: $(this).find('.product-description').html()
});
})
.find('.product-view')
.click(function() {
var $thisListItem = $(this).parents('ul li');
var index = $('#products > li').index($thisListItem);
this.index = index;
showProduct();
});
};
function showProduct() {
var index = this.index;
console.log('INDEX = ' + index);
// hide current data
$('#product-info')
.show()
.find('.hide-me, #product-gallery')
.hide()
.parent()
.find('.loading')
.show();
// get data contained in the page
$('#product-info')
.find('h3')
.html(products[index].title)
.parent()
.find('#dimensions')
.html(products[index].dimensions)
.parent()
.find('#product-description')
.html(products[index].description)
// get id & then product extra info
var id = $('#products > li').eq(index).attr('id').replace(/id-/, '');
var downloadPath = PATH_BASE + 'downloads/';
var imagePath = PATH_BASE + 'images/products/'
$.getJSON(PATH_BASE + 'products/get/' + id + '/',
function(data){
var file = '';
var images = [];
file = data.file;
images = data.images;
// show file list item if there is a file
if (file) {
$('#spex-sheet').show().find('a').attr( { href: downloadPath + file } );
} else {
$('#spex-sheet').hide();
}
// image gallery
if (images.length != 0) {
$('#product-gallery').show();
// preload image thumbnails
$.each(images, function(i, image){
var img = new Image();
img.src = imagePath + 'thumb-' + image;
img = null;
});
// set first image thumbail and enlarge link
if (images[0]) {
$('#enlarge-image').show().find('a').attr({ href: imagePath + images[0] });
$('#product-gallery img').attr ( { src: imagePath + 'thumb-' + images[0]} )
}
console.log(images);
// setup gallery
var currentImage = 0;
clearInterval(cycle);
console.log(cycle);
var cycle = setInterval(function() {
console.log(currentImage + ' = ' + index);
if (currentImage == images.length - 1) {
currentImage = 0;
} else {
currentImage ++;
};
var obj = $('#product-gallery');
var imageSource = imagePath + 'thumb-' + images[currentImage];
obj.css('backgroundImage','url(' + imageSource +')');
obj.find('img').show().fadeOut(500, function() { $(this).attr({src: imageSource}) });
$('#enlarge-image a').attr({ href: imagePath + images[currentImage] });
}, 5000);
// setup lightbox
$("#enlarge-image a").slimbox({/* Put custom options here */}, null, function(el) {
return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
});
} else {
// no images
$('#enlarge-image').hide();
$('#product-gallery').hide();
};
// show the product info
$('#product-info')
.find('.hide-me')
.remove('#product-gallery, #spex-sheet')
.show()
.parent()
.find('.loading')
.hide();
});
};
};
The important function is showProduct(). Now generally I don't write JS like this, but I decided to give it a go. My problem is, that when a user clicks a 'more' button, and it displays the prouduct, it doesn't reset the simple slideshow (the images var is reset, I think it has to do with the setInterval() maybe, or it seems it's making a new instance of showProduct() everytime).
Does anyone know what I'm doing wrong?
I had to reformat your code to really understand what was going on. Anyway, I found the problem with the code.
As you guessed correctly, problem is with the scope but not with the variable 'images' but with variable 'cycle'. Why?
This line
var cycle = setInterval(function() {
Always creates a new local cycle variable (notice the 'var') which is not accessible when showProduct gets called the second time. This means that this line
clearInterval(cycle);
is essentially useless as it always passes null to the clearInterval function and doesn't clear anything. This means that as you keep clicking on 'more', you are creating more and more setInterval function calls, never clearing the old ones.
Anyway, I have refactored your code a little bit, I think this should work as expected. The changes I did are:
Removed this.index variable. It's better to pass 'index' to showProduct instead of setting this.index before showProduct method call and making showProduct use that variable. Also, why did you prefix the variable with 'this'?
Declared cycler variable outside the scope of showProduct, local to the productDisplay method. This insures that you can access cycler during different showProduct calls.
Created smaller functions named showFile, showGallery, showProductInfo to make it easier to understand/maintain code.
Let me know if you have any questions OR if the code still doesn't work.
function productDisplay() {
//Instead of keeping this.index variable, it's better to make showProduct function
//take index variable.
products = [];
setupProductDisplay();
processListItems();
//We have to define cycler outside the showProduct function so that it's maintained
//in between showProduct calls.
var cycler = null;
showProduct(0);
function setupProductDisplay()
{
var productInfoBoxHtml = '<div id="product-info"><h3 class="hide-me"></h3><span id="dimensions" class="hide-me"></span><div id="product-gallery"><img alt="" src="" /></div><ul id="product-options" class="hide-me"><li id="spex-sheet">Download full spex sheet</li><li id="enlarge-image">Enlarge image</li></ul><div id="product-description" class="hide-me"></div><span id="top"></span><span id="bottom"></span><span id="side"></span><span class="loading"></span></div>';
$('#products').after(productInfoBoxHtml);
}
function processListItems()
{
$('#products > li')
.append('<span class="product-view">View</span>')
.filter(':even')
.addClass('even')
.end()
.each(
function()
{
products.push({
id: $(this).find('h3').html(),
title: $(this).find('h3').html(),
dimensions: $(this).find('.dimensions').html(),
description: $(this).find('.product-description').html()
});
})
.find('.product-view')
.click( function()
{
var $thisListItem = $(this).parents('ul li');
showProduct($('#products > li').index($thisListItem));
}
);
};
function showFile(file)
{
if (file)
{
$('#spex-sheet').show().find('a').attr( { href: downloadPath + file } );
}
else
{
$('#spex-sheet').hide();
}
}
function showGallery(images)
{
if(! images || !images.length || images.length == 0)
{
$('#enlarge-image').hide();
$('#product-gallery').hide();
return;
}
$('#product-gallery').show();
$.each(images,
function(i, image)
{
var img = new Image();
img.src = imagePath + 'thumb-' + image;
img = null;
});
// set first image thumbail and enlarge link
if (images[0])
{
$('#enlarge-image').show().find('a').attr({ href: imagePath + images[0] });
$('#product-gallery img').attr ( { src: imagePath + 'thumb-' + images[0]} )
}
var currentImage = 0;
clearInterval(cycler);
cycler = setInterval(
function()
{
currentImage = currentImage == images.length - 1 ? 0 : currentImage++;
var obj = $('#product-gallery');
var imageSource = imagePath + 'thumb-' + images[currentImage];
obj.css('backgroundImage','url(' + imageSource +')');
obj.find('img').show().fadeOut(500, function() { $(this).attr({src: imageSource}) });
$('#enlarge-image a').attr({ href: imagePath + images[currentImage] });
}, 5000);
$("#enlarge-image a").slimbox({/* Put custom options here */}, null, function(el) {
return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
});
};
function showProductInfo()
{
$('#product-info')
.find('.hide-me')
.remove('#product-gallery, #spex-sheet')
.show()
.parent()
.find('.loading')
.hide();
}
function showProduct(index)
{
$('#product-info')
.show()
.find('.hide-me, #product-gallery')
.hide()
.parent()
.find('.loading')
.show();
// get data contained in the page
$('#product-info')
.find('h3')
.html(products[index].title)
.parent()
.find('#dimensions')
.html(products[index].dimensions)
.parent()
.find('#product-description')
.html(products[index].description)
// get id & then product extra info
var id = $('#products > li').eq(index).attr('id').replace(/id-/, '');
var downloadPath = PATH_BASE + 'downloads/';
var imagePath = PATH_BASE + 'images/products/'
$.getJSON(PATH_BASE + 'products/get/' + id + '/',
function(data)
{
showFile(data.file);
showGallery(data.image);
showProductInfo();
});
};
};
If you don't define your variables with var (e.g. var images = ...;) then they will be considered global variables (members of the window object).
If you define them with var then they are visible to the whole function (even before the variable is declared) they are declared in.
I can't immediately see what the problem is, but I would recommend minimizing the scope of your variables - if they don't need to be global then make sure they aren't global.