Dynamically replacing the content for large list - javascript

I am trying to render child elements of an element if the element is in view or removing the content if not in view like below on scroll event like below
list.addEventListener('scroll', function () {
var elements = document.querySelectorAll('.aBox');
var toBe = counter - 1 - elements.length;
for (var i = 0; i < elements.length; i++) {
var inView = visibleY(elements[i]),
ele = elements[i].querySelector('.item');
if (inView === false && ele) {
console.log("Not in visible, keeping it none");
var height = elements[i].clientHeight;
elements[i].style.height = height + "px";
elements[i].innerHTML = "";
} else if(!ele){
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
elements[i].innerHTML = str;
}
}
});
It seems working but if I have a look at the DOM this is not working as expected. Someone please help me to find the problem, fiddle.
Update
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
if (typeof minArray === "object") {
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
}
cb();
}, function () {
callback()
});
}
Fiddle

Hi I have solved this problem. Posting here, so that it will be more helpful for people who want to work on mobiles to display very large lists with virtual scrolling
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = "Hello Dudes..." + i;
}
Array.prototype.chunk = function (chunkSize) {
var array = this;
return [].concat.apply([],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
}));
}
arr = arr.chunk(50);
var list = document.getElementById('longList');
var button = document.getElementById('loadMore');
var counter = arr.length,
aBoxLen = 1;
function appendBox() {
var div = document.createElement('div'),
str = "";
div.className = "aBox";
var minArray = arr[counter - aBoxLen];
for (var i = 0; i < minArray.length; i++) {
str += "<div class='item'>" + minArray[i] + "</div>";
}
div.innerHTML = str;
div.setAttribute('index', counter - aBoxLen);
var box = document.querySelector('.aBox');
if (box) {
list.insertBefore(div, box);
} else {
list.appendChild(div);
}
aBoxLen += 1;
}
appendBox();
button.addEventListener('click', function () {
appendBox();
});
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
console.log(element.getAttribute('index'));
var minArray = arr[element.getAttribute('index')],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
cb();
}, function () {
// callback()
});
}
var delay = false;
var timeout = null;
list.addEventListener('touchmove', function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
updateData();
}
}, delay);
});
None of the solutions were specifically designed for mobiles, so I have implemented this.
I think there is lots of space for improvement in this. If anybody want to improve it, please feel free to make it
Demo

Related

Javascript class method declaration throwing token error

I am having a problem defining a class method:
this.method = function(){...}
I get an error thrown at the "." after "this".
If I declare the method directly using method(){...}, I am unable to reference it in other methods as it shows that the method is undefined.
The method I want to deifne is shuffleBoard(). How do I do it?
class Board {
constructor(size,boardId){
this.boardId = boardId;
switch(size){
case "medium":
var boardSize = 560;
var tiles = 7*7;
break;
case "large":
boardSize = 720;
tiles = 9*9;
break;
default:
boardSize = 320;
tiles = 4*4;
break;
}
var container = $(this.boardId+" .tiles-container");
var row = 0;
var loopArray = [];
for(var i = 0;i < tiles; i++){
var tile = document.createElement("div");
loopArray.push(i);
var text = i+1;
tile.setAttribute("index",i+1);
tile.id = i+1;
if(i == tiles - 1){
var empty = "empty"
}
tile.setAttribute("class","tile "+empty);
tile.innerText = text;
container.append(tile);
(function(){
tile.onclick = function(){
var tileObject = new Tile(this.getAttribute("index"));
console.log(tileObject.move());
}
})()
var prevRow = row;
if(i%4 == 0 && i != 0){
row++
}
if(row > prevRow){
var positionX = 0;
}
else{
var positionX = (i%4)*80;
}
var positionY = row*80;
tile.style.top=positionY+"px";
tile.style.left=positionX+"px";
console.log(i+"---"+row+"////"+prevRow);
}
setTimeout(function(){this.shuffleBoard(loopArray);},4000);
return container;
}
this.shuffleBoard = function(arr){
var i = 0;
console.log(this.boardId);
$(this.boardId+" .tiles-container tile").forEach(function(el){
var shuffled = shuffle(arr);
el.innerText = shuffled[i];
arr.pop(arr[i]);
i++
});
}
}
It seems like you are using ES6 syntax. In ES6 write functions like
shuffleBoard() {
// rest of the code
}
and to access it use this keyword. like this.shuffleBoard().
To call it in setTimeout, use arrow functions
setTimeout(() => { this.shuffleBoard(loopArray); }, 4000);
1.You have to use an arrow function to keep the scope, because otherwise this would be pointing to the new function created in the timeout.
setTimeout(() => {
this.shuffleBoard(loopArray);
}, 4000);
2.The constructor mustn't return anything because it prevents it from returning the object it constructs
3.jQuery uses .each() to iterate over jQuery objects instead of .forEach().
I put the notes directly in the code as comments as well:
class Board {
constructor(size, boardId) {
this.boardId = boardId;
switch (size) {
case "medium":
var boardSize = 560;
var tiles = 7 * 7;
break;
case "large":
boardSize = 720;
tiles = 9 * 9;
break;
default:
boardSize = 320;
tiles = 4 * 4;
break;
}
var container = $(this.boardId + " .tiles-container");
var row = 0;
var loopArray = [];
for (var i = 0; i < tiles; i++) {
var tile = document.createElement("div");
loopArray.push(i);
var text = i + 1;
tile.setAttribute("index", i + 1);
tile.id = i + 1;
if (i == tiles - 1) {
var empty = "empty"
}
tile.setAttribute("class", "tile " + empty);
tile.innerText = text;
container.append(tile);
(function() {
tile.onclick = function() {
var tileObject = new Tile(this.getAttribute("index"));
console.log(tileObject.move());
}
})()
var prevRow = row;
if (i % 4 == 0 && i != 0) {
row++
}
if (row > prevRow) {
var positionX = 0;
} else {
var positionX = (i % 4) * 80;
}
var positionY = row * 80;
tile.style.top = positionY + "px";
tile.style.left = positionX + "px";
console.log(i + "---" + row + "////" + prevRow);
}
setTimeout(() => { //use arrow function to keep the scope
this.shuffleBoard(loopArray);
}, 4000);
//return container; returning the container here prevents the constructor from returning the constructed object
}
shuffleBoard(arr) {
var i = 0;
console.log(this.boardId);
$(this.boardId + " .tiles-container tile").each(function(el) { //jQuery uses .each instead of forEach
var shuffled = shuffle(arr);
el.innerText = shuffled[i];
arr.pop(arr[i]);
i++
});
}
}
let board = new Board("medium", "myboard");
console.log(board.shuffleBoard);
board.shuffleBoard([]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
shuffleBoard = function(arr){
// rest of code
})
Then you can use method as:
let board = new Board()
board.shuffleBoard()
way1:move this.propertyName to constructor
class Board{
constructor(size,boardId){
this.boardId = boardId;
switch(size){
case "medium":
var boardSize = 560;
var tiles = 7*7;
break;
case "large":
boardSize = 720;
tiles = 9*9;
break;
default:
boardSize = 320;
tiles = 4*4;
break;
}
var container = $(this.boardId+" .tiles-container");
var row = 0;
var loopArray = [];
for(var i = 0;i < tiles; i++){
var tile = document.createElement("div");
loopArray.push(i);
var text = i+1;
tile.setAttribute("index",i+1);
tile.id = i+1;
if(i == tiles - 1){
var empty = "empty"
}
tile.setAttribute("class","tile "+empty);
tile.innerText = text;
container.append(tile);
(function(){
tile.onclick = function(){
var tileObject = new Tile(this.getAttribute("index"));
console.log(tileObject.move());
}
})()
var prevRow = row;
if(i%4 == 0 && i != 0){
row++
}
if(row > prevRow){
var positionX = 0;
}
else{
var positionX = (i%4)*80;
}
var positionY = row*80;
tile.style.top=positionY+"px";
tile.style.left=positionX+"px";
console.log(i+"---"+row+"////"+prevRow);
}
setTimeout(function(){this.shuffleBoard(loopArray);},4000);
this.shuffleBoard = function(arr) {
var i = 0;
console.log(this.boardId);
$(this.boardId + " .tiles-container tile").forEach(function(
el
) {
var shuffled = shuffle(arr);
el.innerText = shuffled[i];
arr.pop(arr[i]);
i++;
});
}
return container;
}
}
way2:change this.propertyName to a method in className.prototype
class Board {
constructor(size, boardId) {
this.boardId = boardId;
switch (size) {
case "medium":
var boardSize = 560;
var tiles = 7 * 7;
break;
case "large":
boardSize = 720;
tiles = 9 * 9;
break;
default:
boardSize = 320;
tiles = 4 * 4;
break;
}
var container = $(this.boardId + " .tiles-container");
var row = 0;
var loopArray = [];
for (var i = 0; i < tiles; i++) {
var tile = document.createElement("div");
loopArray.push(i);
var text = i + 1;
tile.setAttribute("index", i + 1);
tile.id = i + 1;
if (i == tiles - 1) {
var empty = "empty";
}
tile.setAttribute("class", "tile " + empty);
tile.innerText = text;
container.append(tile);
(function() {
tile.onclick = function() {
var tileObject = new Tile(this.getAttribute("index"));
console.log(tileObject.move());
};
})();
var prevRow = row;
if (i % 4 == 0 && i != 0) {
row++;
}
if (row > prevRow) {
var positionX = 0;
} else {
var positionX = (i % 4) * 80;
}
var positionY = row * 80;
tile.style.top = positionY + "px";
tile.style.left = positionX + "px";
console.log(i + "---" + row + "////" + prevRow);
}
setTimeout(function() {
this.shuffleBoard(loopArray);
}, 4000);
return container;
}
shuffleBoard(arr) {
var i = 0;
console.log(this.boardId);
$(this.boardId + " .tiles-container tile").forEach(function(el) {
var shuffled = shuffle(arr);
el.innerText = shuffled[i];
arr.pop(arr[i]);
i++;
});
}
}

Keep the clicked objects in an array in javascript

I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}

JavaScript increase and decrease font size

I am new to JavaScript. I would like to add to add two buttons for my visitors to control font size. I would like to include two tags - 'p' and 'blockquote". Can you please help me edit this code in order to include both?
var min = 8;
var max = 18;
function increaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
p[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
p[i].style.fontSize = s + "px"
}
}
Thank you.
Here's a working version:
http://jsfiddle.net/ny4p7pg9/
I took the liberty of refactoring a bit the functions to make the code more parameterized.
function changeFontSize(delta) {
var tags = document.querySelectorAll('p,blockquote');
for (i = 0; i < tags.length; i++) {
if (tags[i].style.fontSize) {
var s = parseInt(tags[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += delta;
}
tags[i].style.fontSize = s + "px"
}
}
function increaseFontSize() {
changeFontSize(1);
}
function decreaseFontSize() {
changeFontSize(-1);
}
Instead of using:
p = document.getElementsByTagName('p');
you could, instead use:
elems = document.querySelectorAll('p, blockquote');
(the variable name is irrelevant, and was changed only because the elements are no longer exclusively <p> elements):
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
elems[i].style.fontSize = s + "px"
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
The querySelectorAll() method accepts CSS-style selectors, and returns a (non-live) NodeList, and is supported in all modern browsers, including IE from version 8 onwards.
That said, it's probably better to increase the font-size of the <body> element, otherwise font-adjustment is redundant (since other elements will still be unclear), so, instead, I'd suggest:
function increaseFontSize() {
// retrieving, and caching, the <body> element:
var body = document.body,
// finding the current computed fontSize of the <body> element, parsing it
// as a float (though parseInt() would be just as safe, really):
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
// if the currentFontSize is less than the specified max:
if (currentFontSize < max) {
// we set the fontSize of the <body> to the incremented fontSize,
// increasing the current value by 1, and concatenating with the 'px' unit:
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize < max) {
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
References:
document.body.
document.querySelectorAll().
Window.getComputedStyle().

IE8 show hide issue for scrollable table

I have used javascript to creat a scollable table on page load
The visibility of the table is hidden by default.
When i minimize/maximize the page in IE, the browser makes the hidden table visible.
Can any one help me in solving this issue.
The javascript to create scrollable table is as follows
/* Scrollable table */
function setScrollableTableHeight(name,maxrows)
{
var count;
var arrObj = document.getElementsByName(name);
for(count=0;count<arrObj.length;count++)
{
ScrollableTable(arrObj[0], maxrows);
}
}
// set Body width to screen width
function setBodyWidth()
{
objBody = document.getElementsByTagName('body');
objBody[0].style.width = screen.width - 40;
var objDivs = document.getElementsByTagName('div');
for(var i=0;i<objDivs.length;i++)
{
if(objDivs[i].className == "OuterPanel")
{
if(screen.width < 980)
objDivs[0].style.width = 980 - 42;
else
objDivs[0].style.width = screen.width - 42;
break;
}
}
}
function ScrollableTable (tableEl, maxRows, tableWidth) {
var tableHeight = 25 + maxRows * 25;
var numRows = 0;
this.initIEengine = function () {
if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
}
if (this.thead) {
var trs = this.thead.getElementsByTagName('tr');
for (x=0; x<trs.length; x++) {
trs[x].style.position ='relative';
trs[x].style.setExpression("top", "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
}
}
if (this.tfoot) {
var trs = this.tfoot.getElementsByTagName('tr');
for (x=0; x<trs.length; x++) {
trs[x].style.position ='relative';
trs[x].style.setExpression("bottom", "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
}
}
eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");
};
this.initFFengine = function () {
var headHeight = (this.thead) ? this.thead.clientHeight : 0;
var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
var bodyHeight = this.tbody.clientHeight;
this.tbody.setAttribute("id", "dynamicScrollParentfirefox");
var trs = this.tbody.getElementsByTagName('tr');
numRows = trs.length;
var tds;
if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
for (x=0; x<trs.length; x++) {
tds = trs[x].getElementsByTagName('td');
tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
}
}
var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';
};
this.tableEl = tableEl;
this.scrollWidth = 16;
this.originalHeight = this.tableEl.clientHeight;
this.originalWidth = this.tableEl.clientWidth;
/* modified by rmv */
if(parseInt(tableHeight) > this.originalHeight && this.originalHeight!=0)
tableHeight = this.originalHeight;
/* modified by rmv ends*/
this.newHeight = parseInt(tableHeight);
this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;
this.tableEl.removeAttribute('height');
var loverflowParent = document.createElement('div');
loverflowParent.setAttribute("id","dynamicScrollParent");
this.containerEl = this.tableEl.parentNode.insertBefore(loverflowParent, this.tableEl);
this.containerEl.appendChild(this.tableEl);
this.containerEl.style.height = this.newHeight + 'px';
this.containerEl.style.width = this.newWidth + 'px';
var thead = this.tableEl.getElementsByTagName('thead');
this.thead = (thead[0]) ? thead[0] : null;
var tfoot = this.tableEl.getElementsByTagName('tfoot');
this.tfoot = (tfoot[0]) ? tfoot[0] : null;
var tbody = this.tableEl.getElementsByTagName('tbody');
this.tbody = (tbody[0]) ? tbody[0] : null;
if (!this.tbody) return;
if (document.all && document.getElementById && !window.opera) this.initIEengine()
if (!document.all && document.getElementById && !window.opera) this.initFFengine()
}
You can also try to force the table to scroll when the page height changes. You can apply in CSS this attribute to the container of the table: overflow-y:scroll;

How can I auto size this HTML Menu to fit parent width?

I am converting a Drupal 6 theme to Drupal 7, and cant figure this part out. I have the following HTML:
<ul id="nav" class=" scaling-active scaling-ready">
<li>Design</li>
<li>Inspiration</li>
<li>Nature</li>
<li>Photography</li>
<li>Technology</li>
<li>Travel</li>
<li>Tutorials</li>
<li>Urban</li>
<li>Video Games</li>
</ul>
In Drupal 6 this theme was using jquery v1.3.2, but in Drupal 7 jquery 1.4.4 is built in, so the functions don't seem to be working. Here is the jquery function:
$(function(){
clearFormFields({
clearInputs: true,
clearTextareas: false,
passwordFieldText: true,
addClassFocus: "focus",
filterClass: "form-text"
});
initAutoScalingNav({
menuId: "nav",
sideClasses: true
});
ieHover('#nav li');
$('div.gallery-block').fadeGallery({
slideElements:'ul.gallery > li',
pagerLinks:'ul.switcher li'
});
$('div.pictures-box').fadeGallery({
slideElements:'ul.fade-gallery > li',
pagerLinks:'ul.pictures-list li',
title: true
});
});
function initAutoScalingNav(o) {
if (!o.menuId) o.menuId = "nav";
if (!o.tag) o.tag = "a";
if (!o.spacing) o.spacing = 0;
if (!o.constant) o.constant = 0;
if (!o.minPaddings) o.minPaddings = 0;
if (!o.liHovering) o.liHovering = false;
if (!o.sideClasses) o.sideClasses = false;
if (!o.equalLinks) o.equalLinks = false;
if (!o.flexible) o.flexible = false;
var nav = document.getElementById(o.menuId);
if(nav) {
nav.className += " scaling-active";
var lis = nav.getElementsByTagName("li");
var asFl = [];
var lisFl = [];
var width = 0;
for (var i=0, j=0; i<lis.length; i++) {
if(lis[i].parentNode == nav) {
var t = lis[i].getElementsByTagName(o.tag).item(0);
asFl.push(t);
asFl[j++].width = t.offsetWidth;
lisFl.push(lis[i]);
if(width < t.offsetWidth) width = t.offsetWidth;
}
if(o.liHovering) {
lis[i].onmouseover = function() {
this.className += " hover";
}
lis[i].onmouseout = function() {
this.className = this.className.replace("hover", "");
}
}
}
var menuWidth = nav.clientWidth - asFl.length*o.spacing - o.constant;
if(o.equalLinks && width * asFl.length < menuWidth) {
for (var i=0; i<asFl.length; i++) {
asFl[i].width = width;
}
}
width = getItemsWidth(asFl);
if(width < menuWidth) {
var version = navigator.userAgent.toLowerCase();
for (var i=0; getItemsWidth(asFl) < menuWidth; i++) {
asFl[i].width++;
if(!o.flexible) {
asFl[i].style.width = asFl[i].width + "px";
}
if(i >= asFl.length-1) i=-1;
}
if(o.flexible) {
for (var i=0; i<asFl.length; i++) {
width = (asFl[i].width - o.spacing - o.constant/asFl.length)/menuWidth*100;
if(i != asFl.length-1) {
lisFl[i].style.width = width + "%";
}
else {
if(navigator.appName.indexOf("Microsoft Internet Explorer") == -1 || version.indexOf("msie 8") != -1 || version.indexOf("msie 9") != -1)
lisFl[i].style.width = width + "%";
}
}
}
}
else if(o.minPaddings > 0) {
for (var i=0; i<asFl.length; i++) {
asFl[i].style.paddingLeft = o.minPaddings + "px";
asFl[i].style.paddingRight = o.minPaddings + "px";
}
}
if(o.sideClasses) {
lisFl[0].className += " first-child";
lisFl[0].getElementsByTagName(o.tag).item(0).className += " first-child-a";
lisFl[lisFl.length-1].className += " last-child";
lisFl[lisFl.length-1].getElementsByTagName(o.tag).item(0).className += " last-child-a";
}
nav.className += " scaling-ready";
}
function getItemsWidth(a) {
var w = 0;
for(var q=0; q<a.length; q++) {
w += a[q].width;
}
return w;
}
}
In the Drupal 6 version the above code automatically adds the style="width: xx" tags to the hyperlinks, which causes the menu to grow the menu buttons to fill the width of its container.
Thanks.
I would suggest throwing out that old javascript and replace with jQuery - seeing as someone else has already solved this problem :
http://tympanus.net/codrops/2010/01/12/self-resizing-navigation-menu-with-jquery/

Categories