How can I load images in a loop correctly? - javascript

I have a loop that calls a function that loads images. It is not working correctly. The images all load but they all get appended to the last div.
For this example, I have three divs on my page:
<div id="opening_0"></div>
<div id="opening_1"></div>
<div id="opening_2"></div>
Javascript:
$.ajax(
{
type: "GET",
url: xml_source, //call this url - SEE XML BELOW
dataType: 'xml',
async: false,
success: function(xml) //if we have data...
{
openings = $(xml).find("opening"); //Find the openings in the xml
mattes_create_openings(openings);
}
});
function mattes_create_openings(openings)
{
$(openings).each(function(i, el) //loop through the openings xml
{
//more code...
var photos_selected_fid = $(el).find("imgsrc").text();
clipX = 0;
clipY = 0;
photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
});
}
function photos_create_preview_image(element, clipX, clipY, photos_selected_fid)
{
photos_selected_opening = element.id; //Sets the selected opening to the div that calls this function
photos_selected_opening_value = photos_selected_opening.replace("opening_", "");
var new_img = new Image();
new_img.onload = function()
{
$(element).empty(); //Empty the div
element.appendChild(new_img); //Append the image to the div
}
new_img.src = SITE_URL + "/system/photo/cf_preview/" + photos_selected_fid; //Set the source of the image
}
XML that is loaded:
<?xml version="1.0"?>
<Order>
<size width="20" height="10">
<width>20</width>
<height>10</height>
</size>
<type>photo</type>
<overlay/>
<Mats selected_type="17" selected_design="81">
<mat layer_name="top">
<item size="0">
<imgsrc>11852997eab43ff5c7b1803692bee608</imgsrc>
<size>0</size>
<cpu/>
<cid>4208</cid>
<id/>
</item>
<fillet index="0">
<imgsrc>5ade25e607b6302691c318a94792e6eb</imgsrc>
<width>0.31</width>
<cid>9349</cid>
<sku>TD00060GL1</sku>
</fillet>
</mat>
</Mats>
<Openings>
<opening>
<item>
<x>7.75</x>
<y>1.75</y>
<width>4.5</width>
<height>6.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>a0d3b6664b2fef68c279c5f58e6af5d6</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
<opening>
<item>
<x>14</x>
<y>2.25</y>
<width>3.5</width>
<height>5.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>148d39e78620ed03dc6bf0fee199ec97</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
<opening>
<item>
<x>2.5</x>
<y>2.25</y>
<width>3.5</width>
<height>5.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>971e9044a3f1fca2291d62d64470a1bd</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
</Openings>
<Moulding>
<imgsrc>5f52a13c425655fa62058418542b95ca</imgsrc>
<width>1.13</width>
<cid>174</cid>
<sku>TD01600B0</sku>
<cpu>0.00</cpu>
</Moulding>
<Glass>
<cid>GAPC</cid>
</Glass>
</Order>
I have a jsfiddle: http://jsfiddle.net/allisonc/am83wp4m/1/
When I run the jsfiddle, it tries set the source as all of them combined (ex: SITE_URL + "/system/photo/cf_preview/" + imgsrc1 + imgsrc2 + imgsrc3)

See: http://jsfiddle.net/allisonc/am83wp4m/2/
var openings = document.createElement("Openings");
var opening1 = document.createElement("opening");
var imgsrc1 = document.createElement("imgsrc");
imgsrc1.appendChild(document.createTextNode("a0d3b6664b2fef68c279c5f58e6af5d6"));
opening1.appendChild(imgsrc1);
openings.appendChild(opening1);
var opening2 = document.createElement("opening");
var imgsrc2 = document.createElement("imgsrc");
imgsrc2.appendChild(document.createTextNode("148d39e78620ed03dc6bf0fee199ec97"));
opening2.appendChild(imgsrc2);
openings.appendChild(opening2);
var opening3 = document.createElement("opening");
var imgsrc3 = document.createElement("imgsrc");
imgsrc3.appendChild(document.createTextNode("971e9044a3f1fca2291d62d64470a1bd"));
opening3.appendChild(imgsrc3);
openings.appendChild(opening3);
var new_openings = $(openings).find("opening");
mattes_create_openings(new_openings);
function mattes_create_openings(openings)
{
$(openings).each(function(i, el) //loop through the openings xml
{
console.log(el);
console.log(i);
//more code...
var photos_selected_fid = $(el).find("imgsrc").text();
console.log(photos_selected_fid);
clipX = 0;
clipY = 0;
//photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
});
}
function photos_create_preview_image(element, clipX, clipY, photos_selected_fid)
{
var photos_selected_opening = element.id; //Sets the selected opening to the div that calls this function
var photos_selected_opening_value = photos_selected_opening.replace("opening_", "");
var new_img = new Image();
new_img.onload = function()
{
$(element).empty(); //Empty the div
element.appendChild(new_img); //Append the image to the div
}
new_img.src = "http://example.com" + "/system/photo/cf_preview/" + photos_selected_fid; //Set the source of the image
}

May be like this
var yourxml = '<your xml data>';
$($.parseXML(yourxml)).find('opening').each(function (index, opening) {
$('#opening_'+index).html('<img src= "http://example.com/system/photo/cf_preview/"' + $(opening).find('imgsrc').text() + ' />');
});

Your code is correct except one thing: I pasted it the following plunker, adjusted to have valid images and separate divs backgrounds and saw an issue in your iteration. Indeed, jQuery's .each() iterates from index 0, which mean you either should use i + 1 or create opening_# containers from 0
http://plnkr.co/edit/8zrEfRfq1dtAeX5voUfK?p=preview
See in the Plunker:
photos_create_preview_image(document.getElementById("opening_" + (i+1)), clipX, clipY);
Note that I separated opening_#s with background color:
<div id="opening_1" style="background:red"></div>
<div id="opening_2" style="background:green"></div>
<div id="opening_3" style="background:blue"></div>
<!-- Include your script AFTER your image containers -->
<script src="script.js"></script>
Ensure your js script is included after your DOM elements (at the end of your HTML's body)

Related

Problem with add attr to img and set path

I have a little problem becouse I read values of labels and after that i want to set img src dependent on value label
Here some code and i see that is img attr don't add
getState generate divs with content
At the end is ajax call function where i get values from database and write them to the dynamically generated labels
The main problem now is then that don't read a values of labels correct becouse I got 3 labels with 3 diffrent states like "Active","Standby","Error" and it set for all Emergency Stop icon
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
console.log(states);
if (states == "Active") {
var Active = "Images/kafle/zebatakActive.svg";
$(this).closest('img').attr("src", Active);
} else if (states == "Standby") {
var Standby = "Images/kafle/kafle_zebatka-01.svg"
$(this).closest('img').attr("src", Standby);
} else if (states == "Error") {
var error = "Images/kafle/kafle_zebatka-01.svg";
$(this).closest('img').attr("src", error);
} else if (states == "Setting") {
var Settings = "Images/kafel/kafle_zebatka-03.svg"
$(this).closest('img').attr("src", Settings);
} else {
var Emergency = "Images/kafle/kafle_status-yel-yel.svg";
$(this).closest('img').attr("src", Emergency);
}
});
}
function getState() {
try {
$.ajax({
type: "POST",
url: "Default.aspx/jsrequest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ajax").empty();
$.each(data, function () {
$("#ajax").append('<div id="ajaxcontent"></div>');
$("#ajaxcontent").addClass("ajaxcontent");
$.each(this, function (k,v) {
$("#ajaxcontent").append('<div class="view">' + ' <label id="IdOfMachine">' + v.MachineId + '</label>'
+ '<label class="MachineState" name="Values" data-id= "' + v.MachineId + ' " > ' + v.CurrentStatus + '</label > '
+ '<img class="ChangeImg" data-id="' + v.MachineId + '"> ' + '</img > '
+ '<label id="MachineName">' + v.MachineName + '</label>' + '</div>');
});
});
},
error: function (response) {
alert("cos źle")
}
});
} catch (err) { }
}
public static List<StateOfMachine> jsrequest()
{
List<StateOfMachine> MachineState = new List<StateOfMachine>();
string DBInfo = #"Data Source=STACJA45;Initial Catalog=AutoRefresh;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string sqlrequest = "Select MachineID,CurrentStatus,MachineName from MachineStates";
SqlConnection connection = new SqlConnection(DBInfo);
SqlCommand command = new SqlCommand(sqlrequest, connection);
connection.Open();
SqlDataReader DataReader = command.ExecuteReader();
while (DataReader.Read()) {
StateOfMachine machines = new StateOfMachine();
machines.MachineId = DataReader["MachineID"].ToString();
machines.MachineName = DataReader["MachineName"].ToString();
machines.CurrentStatus = DataReader["CurrentStatus"].ToString();
MachineState.Add(machines);
}
DataReader.Close();
command.Dispose();
connection.Close();
return MachineState;
}
first of all, welcome to StackOverflow :)
2 things in your code to avoid in the future:
DRY: Don't Repeat Yourself - every time you're writing the same thing over and over, you're doing it wrong :)
To be precise, always use === instead of == the later will give true for 1 == "1" and it's better to avoid it since the start.
Relating to your issue, apart for repeating yourself and the use of == you are specifying $(this) and that is ok as long as you pass a jQuery event because it's a self function, the object this is not what you are assuming.
your code could be changed to something as:
function ChangeImage() {
var labels = $('label[data-id]');
$.each(labels, function (i, x) {
var url = '';
var path = 'Images/kafle';
var state = $(x).text();
switch(state) {
case "Active": url = path + "/zebatakActive.svg"; break;
case "Standby": url = path + "/kafle_zebatka-01.svg"; break;
case "Error": url = path + "/kafle_zebatka-01.svg"; break;
case "Setting": url = path + "/kafle_zebatka-03.svg"; break;
default: url = path + "/kafle_status-yel-yel.svg"; break;
}
$('img[data-id="' + state + '"]').attr("src", url);
console.log({path, state, url});
});
}
code edited from comments
remove closet() and put find()
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
switch(states)
{
case "Active":
$(this).find('img').attr("src","Images/kafle/zebatakActive.svg");
break;
case "Standby":
$(this).find('img').attr("src", "Images/kafle/kafle_zebatka-01.svg");
break;
case "Error":
$(this).find('img').attr("src", "Images/kafle/kafle_zebatka-01.svg");
break;
case "Setting":
$(this).find('img').attr("src", "Images/kafel/kafle_zebatka-03.svg");
break;
default:
$(this).find('img').attr("src", "Images/kafle/kafle_status-yel-yel.svg");
break;
}
});
}
SOLUTION:
If you are using HTML as in the following code snippet, you can use siblings([selector]) to read the matching sibling element and to change the src of the image.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<img src="#" class="image" height="100" width="100">
<label data-id="1" class="image-link">Active</label>
</div>
<div>
<img src="#" class="image" height="100" width="100">
<label data-id="2" class="image-link">Emergency</label>
</div>
<button onclick="changeImage()">Change</button>
<script>
function changeImage() {
let labels = $('label[data-id]');
$.each(labels, function (i, x) {
var states = $(x).text();
if (states == "Active") {
var Active = "https://atlas-content-cdn.pixelsquid.com/stock-images/golden-soccer-ball-3yLR9z1-600.jpg";
$(this).siblings('img').attr( {"src": Active });
} else {
var Emergency = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
$(this).siblings('img').attr("src", Emergency);
}
});
}
</script>
</body>
</html>

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

how to link pagination to pagescroll in jquery?

I have created a carousel in javascript to show multiple contents either by using page scroll or by clicking a button. I have used viewpager.js for this purpose. I have added a pagination at the bottom which works fine when the buttons are clicked. I am unable to figure out how to link it to the page scroll. Any help is appreciated. My code:
HTML
<div id='prev'>
<button id="btn-prev"><img src='img/orange-towards-left.png'></button>
</div>
<div class='pager'>
<div class='pager_items' id='info'>
</div>
</div>
<div id='next'>
<button id="btn-next"><img src='img/orange-towards-right.png'></button>
</div>
<div id='pagination'>
<ul></ul>
</div>
JS
item_container = document.querySelector('.pager_items');
view_pager_elem = document.querySelector('.pager');
w = view_pager_elem.getBoundingClientRect().width;
items = payerAccArr.length;
item_container.style.width = (items * 100)+ '%';
var child_width = (100 / items) + '%';
var html = "";
document.getElementById('monthInfo').innerHTML=payerAccArr[0].DateKey + " Bill Amount ";
for (var i = 0; i < items; i++) {
html += "<div class=toggle><h4>Payer Account Name</h4> <ul> <li>" + payerAccArr[i].PayerAccountName +
"</li></ul> _______________ <ul><li> "+(payerAccArr[i].TotalAmount).toFixed(2) +
" USD</li> </ul></div>";
}
item_container.innerHTML = html;
for(var i=0;i<items;i++)
item_container.children[i].style.width = child_width;
var htmlStr='<li class="current"></li>';
for(var i=0;i<items-1;i++){
htmlStr += '<li></li>';
}
$('#pagination ul').html(htmlStr);
vp = new ViewPager(view_pager_elem, {
pages: item_container.children.length,
vertical: false,
onPageScroll : function (scrollInfo) {
offset = -scrollInfo.totalOffset;
invalidateScroll();
},
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
}
});
window.addEventListener('resize', function () {
w = view_pager_elem.getBoundingClientRect().width;
invalidateScroll();
});
document.getElementById('btn-prev').addEventListener('click', function (){
vp.previous();
if(index>0){
createDoughnutChart(index--);
}
var li = jQuery("li.current");
if (li.length){
var $prev = li.prev();
if($prev.length == 0)
$prev = $("#pagination li").last().addClass("current");
li.removeClass("current");
$prev.addClass("current");
}
});
Similar code for the next button also has been written.
This issue got solved. I made a change to the onPageChange function by adding the following code. I am now able to link it to both the page scroll and the buttons.
JS:
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
// console.log('page', page);
var li = $("li.current");
var curIndex = li.index();
if(li.length){
var $prev = li.prev();
var $next = li.next();
if(page == $prev.index()){
li.removeClass("current");
$prev.addClass("current");
}
if(page==$next.index()){
li.removeClass("current");
$next.addClass("current");
}
}
}

jQuery close button isnt working

I have the following code:
function getdata(id){
$.ajax({
type: "POST",
url: "mapa_llamadas.php",
data: { 'id' : id },
success: function(data) {
var resultado = $.parseJSON(data);
var html = '';
var contador = 0;
for (var columna in resultado){
contador++;
if(contador == 12){
contador = 1;
}
var num_parcela = resultado[columna]['num_parcela'];
var finca_registral = resultado[columna]['finca_registral'];
var ref_catastral = resultado[columna]['ref_catastral'];
var uso_1 = resultado[columna]['uso_1'];
var uso_2 = resultado[columna]['uso_2'];
var sup_m2_parcela = resultado[columna]['sup_m2_parcela'];
var edif = resultado[columna]['edif'];
var aprov_neto_m2 = resultado[columna]['aprov_neto_m2'];
var situacion = resultado[columna]['situacion'];
var adjudicatario = resultado[columna]['adjudicatario'];
var coord = resultado[columna]['coord'];
html += '<ul><li><strong>Número de parcela:</strong> '+num_parcela+'</li><li><strong>Finca registral:</strong> '+finca_registral+'</li><li><strong>Referencia catastral:</strong> '+ref_catastral+'</li><li><strong>Uso 1:</strong> '+uso_1+'</li><li><strong>Uso 2:</strong> '+uso_2+'</li><li><strong>Superficie:</strong> '+sup_m2_parcela+' m<sup>2</sup></li><li><strong>Edificio:</strong> '+edif+'</li><li><strong>Aprovechamiento neto:</strong> '+aprov_neto_m2+' m<sup>2</sup></li><li><strong>Situación:</strong> '+situacion+'</li><li><strong>Adjudicatario:</strong> '+adjudicatario+'</li></ul>';
///alert(contador + "index:" + columna + "\n value" + resultado[columna]['num_parcela']);
}
$('#mostrarparcela').html('<button title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
}
});
}
This exact line isnt working (it should close the window that appears):
$('#mostrarparcela').html('<button title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
#mostrarparcela are a number of <area></area> tags in my html file.
What am I missing?
You have to add close function to button.
Try with
<button title="Cerrar ventana" class="mfp-close" onclick="javascript:window.close();"><i class="mfp-close"><i class="mfp-close-icn">×</i></button>
I have found what I was missing, this is what I needed to add to make the close button functionality work:
$('#mostrarparcela').html('<button id="close" title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
$( "#close" ).click(function() {
var magnificPopup = $.magnificPopup.instance;
magnificPopup.close();
});

javascript not loading on page

I have created a very simple page at this point and am adding a menu that using javascript to display a submenu. I can't get the javascript to load and I am not getting any errors using Firebug. I have stripped my page down to pretty much bare content except for the javascript, but it still won't load. The CSS associated with the menu does load. I didn't write the javascript, but have a basic concept of how it works.
Here is the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>The Journal</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<link href="http://celt.miamioh.edu/ject/images/favicon.png" rel="shortcut icon">
<script src="http://celt.miamioh.edu/newject/menuscript.js" language="javascript" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="menustyle.css" media="screen, print" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0"><tr><td>
<img src="buttons/button1up.png" border="0" id="button1" vspace="1" hspace="1"><img src="buttons/button2up.png" border="0" id="button2" vspace="1" hspace="1"><img src="buttons/button3up.png" border="0" id="button3" vspace="1" hspace="1"><br>
</td></tr></table>
<p>Test page for javascript functionality.</p>
</body>
</html>
and here is he js:
subInfo[2] = new Array();
subInfo[3] = new Array();
//*** SET SUB MENUS TEXT LINKS AND TARGETS HERE ***//
subInfo[1][1] = new Array("Overview","http://celt.miamioh.edu/newject/about.php","");
subInfo[1][2] = new Array("Free Sample Issue","http://celt.miamioh.edu/newject/issue.php?v=19&n=1","");
subInfo[1][3] = new Array("Editorial Board/Staff","http://celt.miamioh.edu/newject/staff.php","");
subInfo[1][4] = new Array("Manuscript Submission","http://celt.miamioh.edu/newject/submission.php","");
subInfo[2][1] = new Array("Current Issue","http://celt.miamioh.edu/newject/issue.php?v=25&n=2","");
subInfo[2][2] = new Array("Issue Archive","http://celt.miamioh.edu/newject/archive.php","");
subInfo[2][3] = new Array("Special Issue Archive","http://celt.miamioh.edu/newject/special.php","");
subInfo[2][4] = new Array("Search Archive","http://celt.miamioh.edu/newject/search.php","");
subInfo[3][1] = new Array("Journal Subscription","http://celt.miamioh.edu/journals/subscription/subscriptionpage.php","");
subInfo[3][2] = new Array("Order Back Issue","http://celt.miamioh.edu/newject/order_backissues.php","");
subInfo[3][3] = new Array("Order Individual Articles","http://celt.miamioh.edu/newject/order_articles.php","");
//*** SET SUB MENU POSITION ( RELATIVE TO BUTTON ) ***//
var xSubOffset = 9;
var ySubOffset = 34;
//*** NO MORE SETTINGS BEYOND THIS POINT ***//
var overSub = false;
var delay = 1000;
totalButtons = upSources.length;
// GENERATE SUB MENUS
for ( x=0; x<totalButtons; x++) {
// SET EMPTY DIV FOR BUTTONS WITHOUT SUBMENU
if ( subInfo[x+1].length < 1 ) {
document.write('<div id="submenu' + (x+1) + '">');
// SET DIV FOR BUTTONS WITH SUBMENU
} else {
document.write('<div id="submenu' + (x+1) + '" class="dropmenu" ');
document.write('onMouseOver="overSub=true;');
document.write('setOverImg(\'' + (x+1) + '\',\'\');"');
document.write('onMouseOut="overSub=false;');
document.write('setTimeout(\'hideSubMenu(\\\'submenu' + (x+1) + '\\\')\',delay);');
document.write('setOutImg(\'' + (x+1) + '\',\'\');">');
document.write('<ul>');
for ( k=0; k<subInfo[x+1].length-1; k++ ) {
document.write('<li>');
document.write('<a href="' + subInfo[x+1][k+1][1] + '" ');
document.write('target="' + subInfo[x+1][k+1][2] + '">');
document.write( subInfo[x+1][k+1][0] + '</a>');
document.write('</li>');
}
document.write('</ul>');
}
document.write('</div>');
}
//*** MAIN BUTTONS FUNCTIONS ***//
// PRELOAD MAIN MENU BUTTON IMAGES
function preload() {
for ( x=0; x<totalButtons; x++ ) {
buttonUp = new Image();
buttonUp.src = buttonFolder + upSources[x];
buttonOver = new Image();
buttonOver.src = buttonFolder + overSources[x];
}
}
// SET MOUSEOVER BUTTON
function setOverImg(But, ID) {
document.getElementById('button' + But + ID).src = buttonFolder + overSources[But-1];
}
// SET MOUSEOUT BUTTON
function setOutImg(But, ID) {
document.getElementById('button' + But + ID).src = buttonFolder + upSources[But-1];
}
//*** SUB MENU FUNCTIONS ***//
// GET ELEMENT ID MULTI BROWSER
function getElement(id) {
return document.getElementById ? document.getElementById(id) : document.all ? document.all(id) : null;
}
// GET X COORDINATE
function getRealLeft(id) {
var el = getElement(id);
if (el) {
xPos = el.offsetLeft;
tempEl = el.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
return xPos;
}
}
// GET Y COORDINATE
function getRealTop(id) {
var el = getElement(id);
if (el) {
yPos = el.offsetTop;
tempEl = el.offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
// MOVE OBJECT TO COORDINATE
function moveObjectTo(objectID,x,y) {
var el = getElement(objectID);
el.style.left = x;
el.style.top = y;
}
// MOVE SUBMENU TO CORRESPONDING BUTTON
function showSubMenu(subID, buttonID) {
hideAllSubMenus();
butX = getRealLeft(buttonID);
butY = getRealTop(buttonID);
moveObjectTo(subID,butX+xSubOffset, butY+ySubOffset);
}
// HIDE ALL SUB MENUS
function hideAllSubMenus() {
for ( x=0; x<totalButtons; x++) {
moveObjectTo("submenu" + (x+1) + "",-500, -500 );
}
}
// HIDE ONE SUB MENU
function hideSubMenu(subID) {
if ( overSub == false ) {
moveObjectTo(subID,-500, -500);
}
}
//preload();
Any help on what is wrong or even how I can further troubleshoot it myself to find out what is wrong would be appreciated.
I created a copy of your file at JSBin here and can verify that the javascript does indeed run.
I also noticed you have code commented out at the bottom //preload(); and perhaps this is what you are expecting to execute?
If you still are not getting the expected results try adding a debugger; statement and running in Firebug and the code should break on the line you added that code.
Your src link is incorrect, to match the URLs in the js file it should be
http://celt.miamioh.edu/newject/menuscript.js

Categories

Resources