How to prevent thumbnail stretching in javascript - javascript

I'm trying to prevent my thumbnails from stretching on my website when search results are shown.
My website is www.thehungryeurasian.com
To search for a label, select 'I'm hungry for' in navigation bar, then click any of the options below.
This is the javascript that I used:
<script type='text/javascript'>
var thumbnail_mode = "no-float" ;
summary_noimg = 300;
summary_img = 350;
img_thumb_height = 200;
img_thumb_width = 300;
</script>
<script type='text/javascript'>
//<![CDATA[
function removeHtmlTag(strx,chop) {
if(strx.indexOf("<")!=-1) {
var s = strx.split("<");
for(var i=0;i<s.length;i++) {
if(s[i].indexOf(">")!=-1) {
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
function createSummaryAndThumb(pID){
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = summary_noimg;
if(img.length>=1) {
imgtag = '<span style="float:left; padding:0px 10px 5px 0px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height +'px"/></span>';
summ = summary_img;
}
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>';
div.innerHTML = summary;
}
//]]>
</script>
However, every time I've tried to edit the size of the image in CSS, it would edit all the images on my website, rather than just those that appear in the search results.

Set only the following code in your CSS file. Use selectors to target more specific images.
/* CSS */
img { height: auto; }
or
/* CSS */
.post-body img { height: auto; }

Related

How can I fix this photo gallery?

I created or tried to make a Photo Gallery on one of my web pages. It worked perfectly at first, but when the "Show more images" button is clicked, it changes the logo and doesn't show the other added images. (See pictures below). How can I avoid the logo changing and show the rest of the photos?
I really will appreciate if somebody can help me to find the error. Thanks!
Here's the html code:
<h1 class="headings1">ABOUT US</h1>
<article>
<div id="leftarrow">
<p><</p>
</div>
<figure id="fig2">
<img class="about" width="360" height="202" />
</figure>
<figure id="fig3">
<img class="about" width="480" height="270" />
</figure>
<figure id="fig4">
<img class="about" width="360" height="202" />
</figure>
<div id="rightarrow">
<p>></p>
</div>
<div id="fiveButton">
<p>Show more images</p>
</div>
</article>
Here's javascript code:
"use strict"; // interpret document contents in JavaScript strict mode
/* global variables */
var photoOrder = [1,2,3,4,5];
var figureCount = 3;
/* add src values to img elements based on order specified on photoOrder array */
function populateFigures() {
var filename;
var currentFig;
if (figureCount === 3){
for (var i = 1; i < 4; i++) {
filename = "images/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about") [i - 1];
currentFig.src = filename;
}
} else {
for (var i = 0; i < 5; i++) {
filename = "image/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about")[1];
currentFig.src = filename;
}
}
}
/* shift all images one figure to the left, and change values in photoOrder array to match */
function rightArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] + 1) === 6) {
photoOrder[i] = 1;
} else {
photoOrder[i] += 1;
}
populateFigures();
}
}
/* shift all images one figure to the right, and change values in photoOrder array to match */
function leftArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] - 1) === 0) {
photoOrder[i] = 5;
} else {
photoOrder[i] -= 1;
}
populateFigures();
}
}
/* switch to 5-images */
function previewFive() {
//create figure and img elements for fifth image
var articleEl = document.getElementsByTagName("article")[0];
var lastFigure = document.createElement("figure");
lastFigure.id = "fig5";
lastFigure.style.zIndex = "5";
lastFigure.style.position = "absolute";
lastFigure.style.right = "45px"
lastFigure.style.top = "67px";
var lastImage = document.createElement("img");
lastImage.classList = "about";
lastImage.width = "240";
lastImage.height = "135"
lastFigure.appendChild(lastImage);
// articleEl.appendChild(lastFigure);
articleEl.insertBefore(lastFigure, document.getElementById("rightarrow"));
//clone figure element for fifth image and edit to be first image
var firstFigure = lastFigure.cloneNode(true);
firstFigure.id = "fig1";
firstFigure.style.right = "";
firstFigure.style.left = "45px";
// articleEl.appendChild(firstFigure);
articleEl.insertBefore(firstFigure, document.getElementById("fig2"));
//add appropiate src values to two img elements
document.getElementsByTagName("img")[0].src = "images/about_0" + photoOrder[0] + "sm.jpg";
document.getElementsByTagName("img")[4].src = "images/about_0" + photoOrder[4] + "sm.jpg";
figureCount = 5;
//change button to hide extra images
var numberButton = document.querySelector("#fiveButton p");
numberButton.innerHTML = "Show fewer images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewFive, false);
numberButton.addEventListener("click", previewThree, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewFive);
numberButton.attachEvent("onclick", previewThree);
}
}
/* switch to 3-image layout */
function previewThree() {
var articleEl = document.getElementsByTagName("article") [0];
var numberButton = document.querySelector("#fiveButton p");
articleEl.removeChild(document.getElementById("fig1"));
articleEl.removeChild(document.getElementById("fig5"));
figureCount = 3;
numberButton.innerHTML = "Show more images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewThree, false);
numberButton.addEventListener("click", previewFive, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewThree);
numberButton.attachEvent("onclick", previewFive);
}
}
/* Create event listener for left arrow, right arrow and center figure element */
function createEventListeners() {
var leftarrow = document.getElementById("leftarrow");
if (leftarrow.addEventListener) {
leftarrow.addEventListener("click", leftArrow, false);
} else if (leftarrow.attachEvent) {
leftarrow.attachEvent("onclick", leftArrow);
}
var rightarrow = document.getElementById("rightarrow");
if (rightarrow.addEventListener) {
rightarrow.addEventListener("click", rightArrow, false);
}else if (rightarrow.attachEvent) {
rightarrow.attachEvent("onclick", rightArrow);
}
var mainFig = document.getElementsByTagName("img")[1];
if (mainFig.addEventListener) {
mainFig.addEventListener("click", zoomFig, false);
} else if (mainFig.attachEvent) {
mainFig.attachEvent("onclick", zoomFig);
}
var showAllButton = document.querySelector("#fiveButton p");
if (showAllButton.addEventListener) {
showAllButton.addEventListener("click", previewFive, false);
}else if (showAllButton.attachEvent) {
showAllButton.attachEvent("onclick", previewFive);
}
}
/* open center figure in separate window */
function zoomFig() {
var propertyWidth = 960;
var propertyHeight = 600;
var winLeft = ((screen.width - propertyWidth) / 2);
var winTop = ((screen.height - propertyHeight) / 2);
var winOptions = "width = 960, height = 600";
winOptions += ",left=" + winLeft;
winOptions += ",top=" + winTop;
var zoomWindow = window.open("zoom.html", "zoomwin", winOptions);
zoomWindow.focus();
}
/* create event listeners and populate image elements */
function setUpPage() {
createEventListeners();
populateFigures();
}
/* run setUpPage() function when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
window.attachEvent("onload", setUpPage);
}
I have included a tiny library with a constructor called ImgViewer. Admittedly, if you resize the screen vertically, it can be a slight issue, but it's all the time I'm willing to take right now. Hopefully you can learn something from this.
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, ImgViewer; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
node.classList.add(...classNames);
return aC;
}
rC = (node, ...classNames)=>{
node.classList.remove(...classNames);
return rC;
}
tC = (node, className)=>{
node.classList.toggle(className);
return tC;
}
ImgViewer = function(imgArray, imgsWide = 3){
if(imgsWide % 2 === 0){
throw new Error('imgsWide must be odd number');
}
this.container = M('div'); this.leftArrow = M('div'); this.view = M('div');
this.rightArrow = M('div'); this.container.className = 'imgViewer';
this.view.className = 'view';
this.leftArrow.className = this.rightArrow.className = 'arrow';
this.leftArrow.textContent = '<'; this.rightArrow.textContent = '>';
this.container.appendChild(this.leftArrow); this.container.appendChild(this.view); this.container.appendChild(this.rightArrow);
const center = Math.floor(imgsWide/2), iA = [], imA = imgArray.slice();
this.size = ()=>{
const b = this.view.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,l=iA.length; i<l; i++){
iA[i].width = i === center ? w+50 : w;
}
return this;
}
this.create = (where = bod)=>{ // default document.body
where.appendChild(this.container);
const v = this.view, b = v.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,m,l=imgArray.length; i<l; i++){
m = M('img');
m.width = i === center ? w+50 : w;
m.src = imgArray[i]; iA.push(m); // cache all the images
if(i < imgsWide){
if(i === center){
// add a click event to center if you want - I did not
}
else if(i < center){
m.onclick = ()=>{
for(let n=i; n<center; n++){
this.rightArrow.onclick();
}
}
}
else{
m.onclick = ()=>{
for(let n=i; n<imgsWide; n++){
this.leftArrow.onclick();
}
}
}
v.appendChild(m);
}
}
const c = v.children;
const dispImgs = ()=>{
for(let n=0; n<imgsWide; n++){
c[n].src = imA[n];
}
}
this.leftArrow.onclick = ()=>{
imA.push(imA.shift()); dispImgs();
}
this.rightArrow.onclick = ()=>{
imA.unshift(imA.pop()); dispImgs();
}
onresize = this.size;
return this;
}
}
// tiny library above - magic below can be put on another page using a load Event except `}); // end load` line
const imgURLs = [
'https://images.freeimages.com/images/large-previews/afa/black-jaguar-1402097.jpg',
'https://images.freeimages.com/images/large-previews/7e9/ladybird-1367182.jpg',
'https://images.freeimages.com/images/large-previews/535/natural-wonders-1400924.jpg',
'https://images.freeimages.com/images/large-previews/035/young-golden-retriever-1404848.jpg',
'https://images.freeimages.com/images/large-previews/981/cow-1380252.jpg',
'https://images.freeimages.com/images/large-previews/9fc/yet-another-flower-1399208.jpg',
'https://images.freeimages.com/images/large-previews/72c/fox-1522156.jpg',
'https://images.freeimages.com/images/large-previews/e2a/boise-downtown-1387405.jpg',
'https://images.freeimages.com/images/large-previews/f37/cloudy-scotland-1392088.jpg'
];
const imgV = new ImgViewer(imgURLs);
imgV.create();
}); // end load
//]]>
/* css/external.css */
*{ /* size font individually to avoid font whitespace */
box-sizing:border-box; font-size:0; margin:0; padding:0; overflow:hidden;
}
html,body{
width:100%; height:100%;
} /* below is what you need to see - above is set for this example */
.imgViewer{
width:100%; height:100%;
}
.imgViewer,.imgViewer *{
display:flex; justify-content:center; align-items:center;
}
.imgViewer>.arrow{
cursor:pointer; width:32px; height:70px; background:#777; color:#fff; font:bold 14px san-serif;
}
.imgViewer>.view{
width:calc(100% - 32px); height:100%;
}
.imgViewer>.view>img{
cursor:pointer; margin:0 7px; box-shadow:1px 1px 2px;
}
.imgViewer>.view>img:first-child{
margin-left:0;
}
.imgViewer>.view>img:last-child{
margin-right:0;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>ImgViewer</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
</body>
</html>
Of course, I didn't make the dummy window for zooming, but you can ask another question for that!

Creating gallery in html DOM with javascript

I want create in html tags which will create gallery,I have 7 images and I want this images will display one time.this means this code must output 3 rows 7 images.
var img=["sea.jpg","monkey.jpg","birtday.jpg","picture.jpg","nintendo.png","square.png","chrome.png"];
function gallery(galleryWidth,columnCount,gutter,divCount){
var n=0;
document.write('<div class="gallery"style="width:'+galleryWidth+'px">');
while(n<img.length%columnCount){
document.write('<div class="row">');
for(i=0;i<img.length;i++){
document.write('<div class="galItem"style="width:'+(galleryWidth/columnCount-2*gutter)+'px;margin:'+gutter+'px"> <img src="img/'+img[i]+'"/></div>');
img.shift();
}
document.write('</div>');
document.write('<div class="clear"></div>');
n++;
}
document.write("</div>");
}
gallery(240,3,5,7);
your code seem like this.
var img = ["sea.jpg", "monkey.jpg", "birtday.jpg", "picture.jpg", "nintendo.png", "square.png", "chrome.png"];
function gallery(galleryWidth, columnCount, gutter) {
document.write('<div class="gallery" style="width:' + galleryWidth + 'px">');
for (var j = 0; j < img.length; j++) {
var startNewLine = j && !(j % columnCount);
if (startNewLine) {
document.write('<div class="row">');
}
document.write('<div class="galItem" style="width:' + (galleryWidth / columnCount - 2 * gutter) + 'px;margin:' + gutter + 'px"> <img alt="' + img[j] + '"/></div>');
if (startNewLine) {
document.write('</div>');
document.write('<div class="clear"></div>');
}
}
document.write("</div>");
}
gallery(240, 3, 5, 7);
.row {
display: block;
clear: both;
}
.clear {
height: 0;
}
img {
width: 100%;
height: 100%;
min-height:30px;
}
.galItem {
float: left;
}
First thing, avoid document.write. There are far more reliable ways of doing this. Second, do/while and your for loop seem to be getting tangled. This may be what you're trying to do.
var img = ["sea.jpg",
"monkey.jpg",
"birtday.jpg",
"picture.jpg",
"nintendo.png",
"square.png",
"chrome.png"
];
function gallery(galleryWidth, columnCount, gutter, divCount) {
this.width = galleryWidth;
this.cols = columnCount;
this.gutter = gutter;
this.divs = divCount;
var myRow, myDiv, myImg, myClearDiv;
var n = 0;
var myGallery = document.createElement('div');
myGallery.classList.add('gallery');
myGallery.style.width = this.width + "px";
myRow = document.createElement('div');
myRow.classList.add('row');
for (i = 0; i < img.length; i++) {
if (n >= this.cols) {
myGallery.appendChild(myRow);
myClearDiv = document.createElement("div");
myClearDiv.classList.add("clear");
myGallery.appendChild(myClearDiv);
myRow = document.createElement('div');
myRow.classList.add('row');
n = 0;
}
myDiv = document.createElement('div');
myDiv.classList.add('galItem');
myDiv.style.width = this.width / this.cols - 2 * this.gutter + 'px';
myDiv.style.margin = this.gutter + 'px';
// Create the image element, and append it...
myImg = document.createElement('img');
myImg.src = '"img/' + img[i] + '"';
myDiv.appendChild(myImg);
// then, append the div to the row.
myRow.appendChild(myDiv);
n++;
}
myGallery.appendChild(myRow);
myClearDiv = document.createElement("div");
myClearDiv.classList.add("clear");
myGallery.appendChild(myClearDiv);
myRow = document.createElement('div');
myRow.classList.add('row');
var container = document.getElementById("container");
container.appendChild(myGallery);
}
gallery(600, 3, 5, 4);
.galItem {
width: 50px;
height: 50px;
display: inline;
border: 1px dotted blue;
}
<div id="container">
</div>

using javascript to randomise a image in background

I am trying to randomise a image in a background, I am having problems because there is content already in the div
this is what i got so far
<div class="welcome-inner">
<script type="text/javascript">
<!--
var imlocation = "welcome/";
var currentdate = 0;
var image_number = 0;
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(3)
image[0] = 'background1.jpg'
image[1] = 'background2.jpg'
image[2] = 'background3.jpg'
var rand = 60/image.length
function randomimage() {
currentdate = new Date()
image_number = currentdate.getSeconds()
image_number = Math.floor(image_number/rand)
return(image[image_number])
}
document.write("<img src='" + imlocation + randomimage()+ "'>");
//-->
</script>
CONTENT
</div>
the div welcome-inner already has styling in the css
.row-welcome {
border-bottom: 0;
width: 100%;
margin: 0 auto;
overflow: auto;
margin-top: -20px;
background-position: 50% 50%;
background-size: cover;
border-bottom: 1px solid #1e346a;
}
welcome-inner did have a background image but I removed the line to try to get this to work
The problem I am having is that the images are showing up but pushing my content down.
how do I adapt this to make it work?
You're going to need to set the background-image style (if you're using jQuery this will be easier). So, instead of creating an tag which goes in the normal document flow, something more like this:
$("#welcome-inner").style("background-image", imlocation + randomimage());
And change "#welcome-inner" to whatever the selector is for the DOM element you want to set the background-image on.
I think your entire approach is incorrect. Try using .sort(), like:
var doc = document;
function E(e){
return doc.getElementById(e);
}
function range(least, greatest){
var r = [];
for(var i=0,n=least; n<=greatest; i++,n++){
r[i] = n;
}
return r;
}
var rng = range(1, 3);
rng.sort(function(){
return Math.round(Math.random())-0.5;
});
for(var i in rng){
var img = new Image();
img.src = 'welcome/background"+rng[i]+".jpg';
// If you add an id called pickAnId to your welcome-inner className div then
E('pickAnId').appendChild(img);
}

Loading xml data for particular element from xml list with javaScript

I hope that someone will know how to help me with this problem, I am new to javaScript and XML. Basically I have the xml file with list of products, I have managed to dynamically load the data into an ul li list in my html page, the li elements has title and image, and now I need to be able to click on this li element and load remaining data for a specific product into a new page (or div). I am getting the "Uncaught ReferenceError: i is not defined" My question is how could I load the correct remaining data after clicking on a specific product from the list of products. (I hope that my explanation is clear enough) here is my code, the first function produces the ul li list in the html page, the displayPRInfo() function should load the data into showPrInfo div for any product which was clicked.
please help me, any help appreciated , thanks for reading.
function loadProducts() {
var liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
var divOpen=("</p><div class='prod-sq-img'>");
var closingTags=("</div></li>");
var txt;
var image;
var title;
var x=xmlDoc.getElementsByTagName("product");
for (i=0;i<x.length;i++)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
}
function displayPRInfo(i)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
euPriceRet=(x[i].getElementsByTagName("euror")[0].childNodes[0].nodeValue);
euPriceTrade=(x[i].getElementsByTagName("eurot")[0].childNodes[0].nodeValue);
euPriceSet=(x[i].getElementsByTagName("eset")[0].childNodes[0].nodeValue);
minimumQuantity=(x[i].getElementsByTagName("mqty")[0].childNodes[0].nodeValue);
description=(x[i].getElementsByTagName("desc")[0].childNodes[0].nodeValue);
prBigImg=(x[i].getElementsByTagName("pimgfile")[0].childNodes[0].nodeValue);
prInfo=title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
document.getElementById("showPrInfo").innerHTML=prInfo;
}
You can use jQuery to manipulate xml and set onclick events.
function loadProducts() {
var products = $(xmlDoc).find('product');
for (var i = 0; i < products.length; i++) {
$('#ulList').append('<li id="product_' + i + '"><p>' + $(products[i]).find('title').text() + '</p><div class="prod-sq-img">' + $(products[i]).find('imgfile').text() + '</div></li>');
$('#product_' + i).click(displayPRInfo.bind($('#product_' + i), products[i]));
}
}
function displayPRInfo(xmlProduct) {
var title= $(xmlProduct).find('title).text();
var euPriceRet = $(xmlProduct).find('euror').text();
var euPriceTrade = $(xmlProduct).find('eurot').text();
var euPriceSet = $(xmlProduct).find('eset').text();
var minimumQuantity = $(xmlProduct).find('mqty').text();
var description = $(xmlProduct).find('desc').text();
var prBigImg = $(xmlProduct).find('pimgfile').text();
var prInfo = title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
$('#showPrInfo').html(prInfo);
}
I haven't tried the whole script but for sure you have to move this:
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>")
into the for loop
for (i=0; i<x.length; i++) {
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
where acctually i is defined
I found this and it helped me a bit, the thing is that I want to load images by request, not loading them all at once but by clicking a button and set the img src with the xml data, I have this...
<!doctype html>
<html lang="es">
<head>
<style>
#iosslider_nav {
height: 13px;
right: 10px;
/* align right side */
/*left: 10px;*/
/* align left side */
bottom: 10px;
/*position: absolute;*/
/* set if needed */
/*margin-top: 10px;*/
/* remove if position is absolute */
}
#iosslider_nav .btn {
width: 13px;
height: 13px;
background: #eaeaea;
margin: 0 5px 0 0;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
cursor: pointer;
float: left;
/* ie 7/8 fix */
background: url('../images/bull_off.png') no-repeat\9;
}
</style>
</head>
<body>
<div id="ninja_slider"></div>
<div id="iosslider_nav"></div>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var xmlDoc = loadXMLDoc("xml/xml_data.xml");
// generic load xml data function
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // code for IE5 and IE6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", filename, false);
xhttp.send();
return xhttp.responseXML;
}
set_slider();
//set_navigation('xml/xml_data.xml', 'iosslider_nav');
function set_slider() {
var item_div = $(xmlDoc).find('desk');
var item_btn = $(xmlDoc).find('desk');
var item_img = $(xmlDoc).find('desk');
// Object.bind() handler for ie 7/8
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
// create main div's
for (var i = 0; i < item_div.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="" class="ninja_item"></div>');
$('#item_div' + i).on('click', load_current.bind($('#item_div' + i), item_div[i]));
}
// load first element
$('#ninja_slider #item_div0 .item_anchor img').attr('src', $(item_img[0]).find('image').text());
// create nav div's
for (var i = 0; i < item_btn.length; i++) {
$('#iosslider_nav').append('<div id="item_btn' + i + '" class="btn"></div>');
$('#item_btn' + i).on('click', load_current.bind($('#item_btn' + i), item_btn[i]));
}
}
function load_current(xmlData) {
var image = $(xmlData).find('image').text();
var src = image;
//console.log(image);
var item_img = $(xmlDoc).find('desk');
for (var i = 0; i < item_img.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="' + $(item_img[i]).find('image').text() + '" class="ninja_item"></div>');
}
}
function set_navigation(url, id) {
$.ajax({
url: url,
async: false,
type: "GET",
data: "xml",
success: function (xml) {
$(xml).find("desk").each(function () {
var item_nav = document.getElementById(id),
click_item = document.createElement("div");
item_nav.appendChild(click_item);
click_item.className = click_item.className + "btn";
});
}
});
}
</script>
</body>
</html>
hope it makes sense...

javascript problem, rss feed display

my code lists items from an rss feed onto an html page. although, the java script is a little finicky. it won't read some xml feeds, usually the feeds containing list items over 25. I just need another set of eyes to take a look at the code and tell me if i'm missing something obvious.
.js file-----------------------------------------------
//XML CODE
var http_request = false;
var dataFileName = new Array();
dataFileName[1] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml";
//dataFileName[2] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/uk_news/magazine/rss.xml";
//dataFileName[3] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/business/rss.xml";
function getData(dataFileIndex) {
if (window.ActiveXObject) { //IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) { //other
http_request = new XMLHttpRequest();
} else {
alert("your browser does not support AJAX");
}
http_request.open("GET",dataFileName[dataFileIndex],true);
http_request.setRequestHeader("Cache-Control", "no-cache");
http_request.setRequestHeader("Pragma", "no-cache");
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if (http_request.responseText != null) {
processRSS(http_request.responseXML);
} else {
alert("Failed to receive RSS file from the server - file not found.");
return false;
}
}
}
}
http_request.send(null);
}
function processRSS(rssxml) {
RSS = new RSS2Channel(rssxml);
outputData(RSS);
}
function RSS2Channel(rssxml) {
this.items = new Array();
var itemElements = rssxml.getElementsByTagName("item");
for (var i=0; i<itemElements.length; i++) {
Item = new RSS2Item(itemElements[i]);
this.items.push(Item);
}
}
function RSS2Item(itemxml) {
this.title;
this.link;
this.description;
this.pubDate;
this.guid;
var properties = new Array("title", "link", "description", "pubDate", "guid");
var tmpElement = null;
for (var i=0; i<properties.length; i++) {
tmpElement = itemxml.getElementsByTagName(properties[i])[0];
if (tmpElement != null) {
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
}
}
}
function outputData(RSS) {
dataString = "";
for (var i=0; i<RSS.items.length; i++) {
dataString += "<div class='itemBlock'>";
newDate = new Date(RSS.items[i].pubDate);
dateString = (newDate.getMonth()+1) + "/" + newDate.getDate() + "/" + newDate.getFullYear();
dataString += "<div class='itemDate'>" + dateString + "</div>";
dataString += "<div class='itemTitle'><a href='" + RSS.items[i].link + "' target='afps_news'>" + RSS.items[i].title + "</a></div>";
//dataString += "<div class='itemDescription'>" + RSS.items[i].description + "</div>";
dataString += "</div>";
}
document.getElementById('outputBlock').innerHTML = dataString;
}
//SCROLL BAR CODE
var ie=document.all;
var nn6=document.getElementById&&!document.all;
var isdrag=false;
var x,y;
var dobj;
var scrollPercent;
var boxTop;
var maxHeight;
var toppoint;
function movemouse(e) {
if (isdrag) {
//dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
toppoint = (nn6) ? ty + e.clientY - y : ty + event.clientY - y;
boxTop = parseInt(document.getElementById('scrollBarBox').style.top) - scrollBarBoxOffset;
if (toppoint < boxTop) toppoint = boxTop;
boxHeight = parseInt(document.getElementById('scrollBarBox').style.height);
maxHeight = boxTop + boxHeight - parseInt(document.getElementById('scrollBar').style.height);
if (toppoint > maxHeight) toppoint = maxHeight;
dobj.style.top = toppoint + "px";
scrollPercent = toppoint / maxHeight;
document.getElementById('textWindow').style.top = parseInt(0 - (document.getElementById('textWindow').offsetHeight - parseInt(document.getElementById('scrollBarBox').style.height)) * scrollPercent );
return false;
}
}
function selectmouse(e) {
var fobj = nn6 ? e.target : event.srcElement;
var topelement = nn6 ? "HTML" : "BODY";
while (fobj.tagName != topelement && fobj.className != "dragme") {
fobj = nn6 ? fobj.parentNode : fobj.parentElement;
}
if (fobj.className == "dragme") {
isdrag = true;
dobj = fobj;
//tx = parseInt(dobj.style.left + 0);
ty = parseInt(dobj.style.top + 0);
//x = nn6 ? e.clientX : event.clientX;
y = nn6 ? e.clientY : event.clientY;
document.onmousemove = movemouse;
return false;
}
}
document.onmousedown = selectmouse;
document.onmouseup = new Function("isdrag=false;");
html file-------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>TEST</TITLE>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<SCRIPT src="script1.js"></SCRIPT>
<STYLE>BODY {
MARGIN: 0px; FONT: 8pt arial
}
#widgetBody {
BACKGROUND-Color:gray; WIDTH: 240px; POSITION: relative; HEIGHT: 299px
}
#textWindowBox {
LEFT: 63px; OVERFLOW: hidden; WIDTH: 152px; POSITION: absolute; TOP: 70px; HEIGHT: 221px
}
#textWindow {
PADDING-TOP: 7px; POSITION: relative
}
#scrollBarBox {
LEFT: 221px; WIDTH: 12px; POSITION: absolute; TOP: 74px; HEIGHT: 216px
}
#scrollBar {
BACKGROUND: url(images/widget_scroll-handle1.gif) no-repeat; WIDTH: 12px; POSITION: relative; HEIGHT: 40px
}
#defenseLinkLink {
LEFT: 4px; WIDTH: 20px; CURSOR: pointer; POSITION: absolute; TOP: 155px; HEIGHT: 140px; BACKGROUND-COLOR: transparent
}
#defenseLinkLink A {
DISPLAY: block; WIDTH: 20px; HEIGHT: 140px
}
.dragme {
POSITION: relative
}
.itemBlock {
PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 4px; MARGIN: 0px 0px 3px; PADDING-TOP: 0px; BORDER-BOTTOM: #adafb3 1px dotted
}
.itemDate {
FONT-SIZE: 0.9em; COLOR: #666; LINE-HEIGHT: 1.1em
}
.itemTitle {
FONT-WEIGHT: bold; LINE-HEIGHT: 1.1em
}
.itemTitle A {
COLOR: #254a7d; TEXT-DECORATION: none
}
.itemDescription {
}
</STYLE>
<SCRIPT>
var scrollBarBoxOffset = 74;
function init() {
document.getElementById('scrollBarBox').style.top = "74px";
document.getElementById('scrollBarBox').style.height = "216px";
document.getElementById('scrollBar').style.height = "40px";
}
</SCRIPT>
<META content="MSHTML 6.00.6001.18294" name=GENERATOR></HEAD>
<BODY onload=init()>
<DIV id=widgetBody>
<DIV id=textWindowBox>
<DIV id=textWindow>
<DIV id=outputBlock></DIV></DIV></DIV>
<DIV id=scrollBarBox>
<DIV class=dragme id=scrollBar></DIV></DIV>
<DIV style="CLEAR: both"></DIV></DIV>
<SCRIPT language=javaScript>getData(2)</SCRIPT>
</BODY></HTML>
Ok, got it working.
2 issues.
army.mil does not resolve! Please use "www.army.mil" instead.
IN RSS2Item replace this line:
if (tmpElement != null) {
with this:
if (tmpElement != null && tmpElement.childNodes[0]) {
Oh man, why are you using XMLHttpRequest directly? Use a library for that, and make your life easier :)
You could be running into cross-site scripting security problems. If the RSS feeds exist on a different domain than the page running the JavaScript, the browser will not let your JavaScript make the requests.
dataFileName[1] = "http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml";
Unless you are (a) a script running from the BBC, or (b) a browser extension, you cannot make an XMLHttpRequest to that server.
dataString += "<div class='itemTitle'><a href='" + RSS.items[i].link
HTML/script injection. If you insist on rolling innerHTML instead of using simple DOM methods you must do HTML escaping to turn <&" into <&".
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
Don't use eval, except in the very few unusual cases you need it. This isn't one of them; you can access a JavaScript property by name using:
this[properties[i]]= tmpElement.firstChild.data;
Also, and this is probably where the unreliability is coming in, you can't be sure there will be a single child Text node. If there is no content in that element, firstChild/childNodes[0] will not exist and you will get an exception. If there is complex content in the element (which normally there shouldn't be, but for RSS 0.9 there can be as unencoded HTML), firstChild.nodeValue won't contain the text content of the element. Instead you would have to walk over the Text node descendents gathering their nodeValue/data.

Categories

Resources