Can't appendChild to parent - javascript

I have div where i want to insert rendered content as a child. This is <div class="top-news-bar"></div>. And i have module for that
var fullNewsService = (function () {
var TEMPLATE_FULL;
var TOP_NEWS_CONTAINER;
function init() {
TEMPLATE_FULL = document.getElementById('template-full-news');
TOP_NEWS_CONTAINER = document.querySelector('.top-news-bar');
TOP_NEWS_CONTAINER.addEventListener('click', handleShowClick);
}
function handleShowClick(event) {
var target = event.target;
if (target.type != 'button')return;
while (!target.hasAttribute('data-id')) {
target = target.parentNode;
}
var id = target.getAttribute('data-id');
var templ = renderFullNews(id);
TOP_NEWS_CONTAINER.appendChild(templ);
}
function renderFullNews(id) {
var article = articlesService.getArticle(id);
var template = TEMPLATE_FULL;
template.content.querySelector('.top-image-full').style.backgroundImage = "url(" + article.picture + ")";
template.content.querySelector('.full-left').innerHTML = article.author;
var description = template.getElementsByClassName('full-right');
template.content.querySelector('.title-full').innerHTML = "<h5>" + article.title + "</h5>";
template.content.querySelector('.content-full').textContent = article.summary;
return template.content.querySelector('.full-news-wrapper').cloneNode(true);
}
return {
init: init,
}
}());
document.addEventListener('DOMContentLoaded', startApp);
function startApp() {
fullNewsService.init();
}
And when i click on button i get id correctly and template genereated successfully.But nothing happens,no erros and no appending.My html http://pastebin.com/jHxH6zPa

Related

How to invoke IIFE function from external file in useEffect?

I was able to run scoper.js function by using script tag <script src="...">. Now I took that scoper.js function out of src and placed them in different file then try to invoke that function in App.js by importing it. But I'm having no luck. I tried window.onload and even setTimeout, but nothing works. My only guess is scoper.js is called immediately by IIFE so needs to be invoked differently if not invoking it by script tag? Please help.(If called successfully, "Hello World" should be in red color.)https://codesandbox.io/s/stylesheet-scoping-b0k9pp?file=/src/App.js
App.js
import React, { useEffect } from "react";
import "./styles.css";
import { scoper } from "./scoper.js";
export default function App() {
useEffect(() => {
const script = document.createElement("script");
script.src =
"https://cdn.rawgit.com/thomaspark/scoper/5de04619/scoper.min.js";
script.async = true;
// document.body.appendChild(script); // this method works
window.onload = function () {
scoper(); // this not working
};
let style = document.createElement("style");
style.setAttribute("scoped", "");
style.innerHTML =
".Puma {" +
"color: purple;" +
"font-size: 50px;" +
"text-align: left;" +
"}";
let main = document.getElementById("raptors");
main.appendChild(style);
}, []);
return (
<>
<div id="lakers" className="Puma">
<div>Hello World!</div>
</div>
<div id="raptors" className="Puma">
<h1>Raptors win!</h1>
</div>
</>
);
}
scoper.js
function scoperInit() {
var style = document.createElement("style");
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
style.sheet.insertRule("body { visibility: hidden; }", 0);
}
function scoper(css, prefix) {
console.log("css is ", css);
console.log("prefix is ", prefix);
var re = new RegExp("([^\r\n,{}]+)(,(?=[^}]*{)|s*{)", "g");
css = css.replace(re, function (g0, g1, g2) {
if (
g1.match(/^\s*(#media|#.*keyframes|to|from|#font-face|1?[0-9]?[0-9])/)
) {
return g1 + g2;
}
if (g1.match(/:scope/)) {
g1 = g1.replace(/([^\s]*):scope/, function (h0, h1) {
if (h1 === "") {
return "> *";
} else {
return "> " + h1;
}
});
}
g1 = g1.replace(/^(\s*)/, "$1" + prefix + " ");
return g1 + g2;
});
return css;
}
function scoperProcess() {
var styles = document.body.querySelectorAll("style[scoped]");
if (styles.length === 0) {
document.getElementsByTagName("body")[0].style.visibility = "visible";
return;
}
var head = document.head || document.getElementsByTagName("head")[0];
for (var i = 0; i < styles.length; i++) {
var style = styles[i];
var css = style.innerHTML;
if (css && style.parentElement.nodeName !== "BODY") {
var id = "scoper-" + i;
var prefix = "#" + id;
var wrapper = document.createElement("span");
wrapper.id = id;
var parent = style.parentNode;
var grandparent = parent.parentNode;
grandparent.replaceChild(wrapper, parent);
wrapper.appendChild(parent);
style.parentNode.removeChild(style);
var newstyle = document.createElement("style");
newstyle.setAttribute("data-scoped-style-for", id);
var csses = scoper(css, prefix);
if (newstyle.styleSheet) {
newstyle.styleSheet.cssText = csses;
} else {
newstyle.appendChild(document.createTextNode(csses));
}
head.appendChild(newstyle);
}
}
document.getElementsByTagName("body")[0].style.visibility = "visible";
}
function scoperReset() {
var styles = document.head.querySelectorAll("style[data-scoped-style-for]");
for (var i = 0; i < styles.length; i++) {
var style = styles[i];
var wrapperElementId = style.getAttribute("data-scoped-style-for");
var wrapperEl = document.getElementById(wrapperElementId);
if (wrapperEl) {
// Node may have disappeared, in that case nothing should happen
var css = style.innerHTML;
var resettedCss = css.replace("#" + wrapperElementId + " ", "");
var parent = wrapperEl.parentNode;
var targetEl = wrapperEl.childNodes[0];
parent.replaceChild(targetEl, wrapperEl);
var scopedStyle = document.createElement("style");
scopedStyle.setAttribute("scoped", "true");
if (scopedStyle.styleSheet) {
scopedStyle.styleSheet.cssText = resettedCss;
} else {
scopedStyle.appendChild(document.createTextNode(resettedCss));
}
targetEl.appendChild(scopedStyle);
}
style.parentNode.removeChild(style);
}
}
function scoperRestart() {
scoperReset();
scoperProcess();
}
(function () {
"use strict";
if (
typeof document === "undefined" ||
"scoped" in document.createElement("style")
) {
return;
}
scoperInit();
if (document.readyState === "complete" || document.readyState === "loaded") {
scoperProcess();
} else {
document.addEventListener("DOMContentLoaded", scoperProcess);
}
})();
if (typeof exports !== "undefined") {
exports.scoper = scoper;
}

i want to make my shoppingcart local so every time i refresh the page my stuff still needs to be in there but i just dont find the right way to do it

This is my code but I don't know where to start to add localstorage.
I am really trying every website for help because I just can't find it.
var _currentArr;
var _ItemsInCart = [];
var _totalPayment = 0;
function getArticle(item, addDetails) {
var article = document.createElement("article");
var h3 = document.createElement("H3");
h3.appendChild(document.createTextNode(item.title));
article.appendChild(h3);
var figure = document.createElement("FIGURE");
var img = document.createElement('img');
img.src = 'images/'+item.img;
var figcaption = document.createElement('figcaption');
figcaption.textContent = 'Meal by: '+item.cook;
figure.appendChild(img);
figure.appendChild(figcaption);
article.appendChild(figure);
// if need details
if (addDetails) {
var dl = document.createElement("dl");
var dt1 = document.createElement("dt");
var dd1 = document.createElement("dd");
dt1.textContent = 'calories:';
dd1.textContent = item.calories;
dl.appendChild(dt1);
dl.appendChild(dd1);
var dt2 = document.createElement("dt");
var dd2 = document.createElement("dd");
dt2.textContent = 'servings:';
dd2.textContent = item.servings;
dl.appendChild(dt2);
dl.appendChild(dd2);
var dt3 = document.createElement("dt");
var dd3 = document.createElement("dd");
dt3.textContent = 'days to book in advance:';
dd3.textContent = item.book;
dl.appendChild(dt3);
dl.appendChild(dd3);
var dt4 = document.createElement("dt");
var dd4 = document.createElement("dd");
dt4.textContent = 'type:';
dd4.textContent = item.type;
dl.appendChild(dt4);
dl.appendChild(dd4);
article.appendChild(dl);
}
// info div
var div = document.createElement("DIV");
div.setAttribute("class", "info");
var p = document.createElement("P");
p.textContent = '€'+item.price+'/pp';
var a = document.createElement("A");
a.setAttribute("href", '#');
a.textContent = 'order';
a.setAttribute("id", item.id);
if (addDetails) {
a.setAttribute("data-item", JSON.stringify(item));
a.className = "order placeOrderInCart";
} else {
a.className = "order orderBtn";
}
// in div
div.appendChild(p);
div.appendChild(a);
article.appendChild(div);
return article;
}
function makeTemplateFromArray(arr) {
_currentArr = [];
_currentArr = arr;
var container = document.getElementById('dynamicContent');
container.innerHTML = '';
if (arr && arr.length) {
arr.forEach(function (item, index) {
// append article
container.appendChild(getArticle(item, false));
});
}
}
function makeTemplateFromItem(item) {
if (item) {
var container = document.getElementById('popupContentWrapper');
container.innerHTML = '';
container.appendChild(getArticle(item, true));
}
}
function showModal(id) {
// find item by id
if (_MEALS && id) {
var found = _MEALS.find(function(item) {
if (item.id === parseInt(id)) {
return true;
}
});
if (found) {
makeTemplateFromItem(found);
}
}
// open modal
document.getElementById('popup').style.display = "block";
}
// sorting
function sortItems() {
var a = _MEALS.slice(0, _MEALS.length);
var k = event.target.value;
makeTemplateFromArray(doSortData(k, a));
}
function doSortData(key, arr) {
var compare = function ( a, b) {
if ( a[key] < b[key] ){
return -1;
}
if ( a[key] > b[key] ){
return 1;
}
return 0;
};
return arr.sort( compare );
}
// change direction
function changeDirection() {
var val = event.target.value;
var a = _currentArr.slice(0, _currentArr.length);
if (val === 'desc') {
makeTemplateFromArray(a.reverse());
} else {
makeTemplateFromArray(_MEALS);
}
}
// search on input
function searchInArray() {
var val = event.target.value;
if (val && val.length > 1) {
val = val.toLowerCase();
var arr = _MEALS.filter(function (item) {
if (item.title.toLowerCase().includes(val)) {
return true;
}
});
makeTemplateFromArray(arr);
} else {
makeTemplateFromArray(_MEALS);
}
}
// prepare options
function prepareOptions(obj) {
var select = document.getElementById('sortby');
Object.keys(obj).forEach(function (key) {
var opt = document.createElement('option');
opt.value = key;
opt.innerHTML = key;
select.appendChild(opt);
});
}
// add item in cart
function addItemInCart(item) {
_ItemsInCart.push(item);
var elem = document.getElementById('cartCounter');
elem.innerHTML = _ItemsInCart.length;
}
// show cart
function showCart() {
// prepare template
var container = document.getElementById('cartItems');
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tfoot = document.createElement("tfoot");
container.innerHTML = '';
var thBody = '<tr><th>Meal</th><th>Price</th></tr>';
thead.innerHTML = thBody;
// tbody
_totalPayment = 0;
_ItemsInCart.forEach(function(item) {
_totalPayment += parseInt(item.price);
var tBodyTemp = '<tr><td>'+item.title+'</td><td>€ '+item.price+'</td></tr>';
tbody.innerHTML += tBodyTemp;
});
// tfoot
var tfootBody = '<tr><td>Total</td><td>€ '+_totalPayment+'</td></tr>';
tfoot.innerHTML = tfootBody;
table.appendChild(thead);
table.appendChild(tbody);
table.appendChild(tfoot);
container.appendChild(table);
// open modal
document.getElementById('cart').style.display = "block";
}
// proceed to checkout
function proceedToCheckout() {
document.getElementById('cartoverview').classList.add('hidden');
document.getElementById('personalinformation').classList.remove('hidden');
}
// validate form submit
function validatepersonalInfoForm() {
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.remove('hidden');
// set values
var val = document.querySelector('input[name="paymentmethod"]:checked').value;
document.getElementById('price').innerHTML = '€ '+_totalPayment;
document.getElementById('paymentmethod').innerHTML = 'in '+val;
}
function setRandomItem() {
var max = _MEALS.length;
var min = 0;
var number = Math.floor(Math.random() * (max - min + 1)) + min;
var item = _MEALS[number];
document.getElementById('mealofthedayimg').src = 'images/'+item.img;
}
// listen on click event for order button
document.body.addEventListener("click", function (event) {
// close modal box
if (event.target.classList.contains("close")) {
document.getElementById('cart').removeAttribute('style');
document.getElementById('popup').removeAttribute('style');
// remove classes from element
document.getElementById('cartoverview').classList.remove('hidden');
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.add('hidden');
}
// open modal box
if (event.target.classList.contains("orderBtn")) {
event.preventDefault();
showModal(event.target.getAttribute("id"));
}
// add item in cart
if (event.target.classList.contains("placeOrderInCart")) {
event.preventDefault();
var item = JSON.parse(event.target.getAttribute("data-item"));
if (item) {
addItemInCart(item);
}
}
});
setTimeout( function() {
// console.log(_MEALS);
makeTemplateFromArray(_MEALS);
prepareOptions(_MEALS[0]);
setRandomItem();
}, 100);
After you add something into _ItemsInCart, set _ItemsInCart as data in localstorage.
Before you want to get something from _ItemsInCart, get data from localstorage first and set it to _ItemsInCart.
_ItemsInCart should always sync with your data in localstorage.
How to use localstorage:
https://www.w3schools.com/html/html5_webstorage.asp
Advice: If possible, separate your DOM manipulating code with your logic code.

Edit an anchor element that is in a child div inside an iframe

I have an iFrame on my page that I need to edit the height of an anchor. This anchor is inside a div element that is also nested in another div element. The iframe is sourced from another site (podbean) and they have supplied script to expose class to the global scope.
https://developers.podbean.com/apidoc/widget#params
This is the script they ask you to include:
var pbs = []; function PB(iframe) {
if (typeof(iframe) == 'string') {
iframe = document.querySelector(iframe);
}
this._iframe = iframe;
pbs.push(this);
this.eventListeners = {};
}
function searchInPBs(win) {
for (var i in pbs) {
if (pbs[i]._iframe.contentWindow == win) {
return i;
}
}
return -1;
}
PB.prototype.bind = function (event, callback) {
if (!(this.eventListeners[event] instanceof Array)) {
this.eventListeners[event] = [];
}
this.eventListeners[event].push(callback);
this._iframe.addEventListener(event, callback,false);
};
PB.prototype.unbind = function (event,callback) {
if(callback){
var index = this.eventListeners[event].indexOf(callback);
this._iframe.removeEventListener(event, callback,false);
if(index !== -1){
this.eventListeners[event].pop(index);
}
}else{
if (this.eventListeners[event] instanceof Array) {
for (var i in this.eventListeners[event]) {
this._iframe.removeEventListener(event, this.eventListeners[event][i],false);
}
this.eventListeners[event] = [];
}
}
};
PB.prototype.reload = function (url, options) {
//check url is player url
if(url.search('/media/player') === -1){
throw new Error("url is not active Podbean player");
}
if (typeof(options) === 'object'){
var urlSplit = url.split('?');
var urlParamsOrig = urlSplit[1].split('&');
var urlParams = {};
for(var k in urlParamsOrig){
var kv = urlParamsOrig[k].split('=');
urlParams[kv[0]] = kv[1];
}
for(k in options){
urlParams[k] = options[k];
}
var queryString = '?api=1';
for(k in urlParams){
queryString += ('&' + k + '=' + urlParams[k]);
}
queryString = queryString.trim('&');
url = urlSplit[0] + queryString;
}
this._iframe.src = url;
};
PB.prototype.play = function () {
this._post({action: "PB.Widget.API.PLAY"});
};
PB.prototype.pause = function () {
this._post({action: "PB.Widget.API.PAUSE"});
};
PB.prototype.next = function () {
this._post({action: "PB.Widget.API.NEXT"});
};
PB.prototype.prev = function () {
this._post({action: "PB.Widget.API.PREV"});
};
PB.prototype.toggle = function () {
this._post({action: "PB.Widget.API.TOGGLE"});
};
PB.prototype.seekTo = function (millisecond) {
this._post({action: "PB.Widget.API.SEEK_TO",value:millisecond});
};
PB.prototype.setVolume = function (volumnNumber) {
this._post({action: "PB.Widget.API.SET_VOLUME",value:volumnNumber});
};
PB.prototype.skip = function (index) {
this._post({action: "PB.Widget.API.SKIP",value:index});
};
//getter
//returns the current volume, in the range of [0, 100].
PB.prototype.getVolume = function(callback){
this._getter('GET_VOLUME',callback);
};
//returns current sound duration in milliseconds.
PB.prototype.getDuration = function(callback){
this._getter('GET_DURATION',callback);
};
//returns current sound position in milliseconds.
PB.prototype.getPosition = function(callback){
this._getter('GET_POSITION',callback);
};
//whether the widget is paused.
PB.prototype.isPaused = function(callback) {
this._getter('GET_PAUSED',callback);
};
//returns the list of sound objects.
PB.prototype.getSources = function(callback){
this._getter('GET_SOURCES',callback);
};
//returns current sound object.
PB.prototype.getCurrentSource = function(callback){
this._getter('GET_CURRENTSOURCE',callback);
};
//returns the index of current sound.
PB.prototype.getCurrentSourceIndex = function(callback){
this._getter('GET_CURRENTSOURCEINDEX',callback);
};
PB.prototype._post = function (msg) {
this._iframe.contentWindow.postMessage(msg, '*');
};
PB.prototype._getter = function (eventName,callback) {
var self = this;
var cb = function(event){
callback(event.data);
self.unbind('PB.Widget.API.CALLBACK.'+eventName,cb);
}
this.bind('PB.Widget.API.CALLBACK.'+eventName,cb);
this._post({action:'PB.Widget.API.'+eventName});
};
window.addEventListener('message', function (event) {
if (event.data.event && event.data.event.search('PB.Widget.') != -1
) {
var index = searchInPBs(event.source);
if (index != -1) {
var e = new Event(event.data.event);
e.data = event.data.data;
pbs[index]._iframe.dispatchEvent(e);
}
}
});
This is the iframe used:
<iframe id="multi_iframe" frameborder="0" scrolling="no" allowfullscreen src="https://www.podbean.com/media/player/multi? playlist=http%3A%2F%2Fplaylist.podbean.com%2F4127923%2Fplaylist_multi.xml&vjs=1&kdsowie31j4k1jlf913=c97955e82971d7fb3b4f8fde2ceb3799e87bdaf9&size=400&skin=13&auto=0&share=1&fonts=Helvetica&download=1&rtl=0" width="100%" height="530"></iframe>
I have tried to change this via Javascript but it is not working as I believe it should.
var widget = new PB('#multi_iframe');
var ifrm = document.getElementById('multi_iframe');
var win = ifrm.contentWindow;
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('player');
function change() {var iframe = widget.form.getElementsByTagName('a')[0].style.height = "600px"};
I just need the a element inside the div id of episode which is in the div id of title to have a style height change.

this.property is undefined: Cannot read property 'classList' of undefined

I'm making something to visualize photographs.
The goal is to select the picture you want in the "list" to make it appear on the main HTML element. But to help you find where you are in the list there's a class putting borders on the element you selected.
The issue :
The function executing with the event this.block.onclick = function () begins well, the .selected is removed from the initial selected element, but when comes this.block.classList.add('selected'); I get this error:
media_visu.js:26 Uncaught TypeError: Cannot read property 'classList' of undefined
I tried to put the function outside, tried className, setAttribute, but nothing changed: my this.block seems to be undefined.
mediavisu.js :
var mediaVisu = function () {
'use strict';
window.console.log('mediaVisu loaded');
var i,
visu = document.querySelector("#img"),
Album = [];
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
this.block.classList.add('selected');
};
Album[Album.length] = this;
}
var test_a = new Photo(1, "test"),
test_b = new Photo(2, "test"),
test_c = new Photo(3, "test"),
test_d = new Photo(4, "test"),
test_e = new Photo(5, "test");
window.console.log(Album);
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i]);
}
};
in the onclick function, this will be the element that was clicked
so you can simply use
this.classList.add('selected');
you may need to rethink using this.place as this wont be the this you think it is .. a common solution is as follows
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
var self = this;
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = self.place;
window.console.log(visu.style.background);
window.console.log(self.place);
this.classList.add('selected');
};
Album[Album.length] = this;
}
alternatively, using bind
function Photo(nb, folder) {
this.block = document.querySelector("#list_img_" + nb);
this.place = 'url(../src/' + folder + '/' + nb + '.jpg)';
this.block.onclick = function () {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
this.block.classList.add('selected');
}.bind(this);
Album[Album.length] = this;
}
note: now you go back to this.block.classList.add('selected') as this is now the this you were expecting before
You can access to it with 'this' (as mentionned in the previous answer) or with the event target :
this.block.onclick = function (e) {
for (i = 0; i < Album.length; i += 1) {
window.console.log(Album[i].block);
if (Album[i].block.classList.contains('selected')) {
Album[i].block.classList.remove('selected');
}
}
visu.style.background = this.place;
window.console.log(visu.style.background);
window.console.log(this.place);
e.target.classList.add('selected');
};

JavaScript CSS Woes - DOM Styling

I have the following as part of a script:
// JSON object out into DOM Nodes, and appends them to 'searchResults' DIV)
var amzJSONCallback = function(tmpData) {
if (tmpData.Item) {
var dv = cel('div');
var gDiv = getEl('searchResults');
gDiv.innerHTML = "";
var tmpItem = tmpData.Item
var ig = cel('img');
ig.setAttribute('src', tmpItem.thumburl);
ig.setAttribute('alt', tmpItem.title);
ig.style.cssText = "border:0px;height:" + tmpItem.thumbdims[0] + "px;width:" + tmpItem.thumbdims[1] + "px";
var a = cel('a');
a.setAttribute('href', tmpItem.url);
a.appendChild(ig);
var dv2 = cel('div');
dv2.style.cssText = "text-align:center;";
dv2.appendChild(a);
gDiv.appendChild(dv2);
var a = cel('a');
a.setAttribute('href', tmpItem.url);
a.appendChild(ctn(tmpItem.title));
dv.appendChild(a);
if (tmpItem.price) {
dv.appendChild(ctn(tmpItem.price));
} else if (tmpItem.lowestnewprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestnewprice));
} else if (tmpItem.lowestusedprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
gDiv.appendChild(dv);
if (tmpItem.desc) {
// RegEx used to strip out extraneous HTML and Entities in Description text
tmpItem.desc = tmpItem.desc.replace(/<.*?>/gi, '');
tmpItem.desc = tmpItem.desc.replace(/&.*?;/gi, ' ');
if (tmpItem.desc.length > 121) {
tmpItem.desc = tmpItem.desc.substr(0, 120) + "..."
}
gDiv.appendChild(cel('br'));
gDiv.appendChild(ctn(tmpItem.desc));
My problem is that I cant style the different elements that get added to the "searchResults" div. Does anyone have any clues on how to style the price in this bit:
if (tmpItem.price) {
dv.appendChild(ctn(tmpItem.price));
} else if (tmpItem.lowestnewprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestnewprice));
} else if (tmpItem.lowestusedprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
Any help would be greatly appreciated.
I would specify a classname in the JavaScript source and let an external CSS file take care of actually applying the formatting to it.
CSS
.styledElement {
font-weight: bold;
}
JavaScript
var eItem = ctn(tmpItem.price);
eItem.className = "styledElement";
dv.appendChild(eItem);
Greg's approach is also good especially if you have to do everything in the JavaScript source.
Instead of:
dv.appendChild(ctn(tmpItem.price));
use something like
var elm = ctn(tmpItem.price);
elm.style.color = 'red';
elm.className = 'amazon-price';
dv.appendChild(elm);
The Whole script:
function getEl(x){return document.getElementById(x)}
function ctn(x){ return document.createTextNode(x) }
function cel(x){ return document.createElement(x) }
function addEvent(obj,type,fn){
if (obj.addEventListener){ obj.addEventListener(type,fn,false)}
else if (obj.attachEvent){
obj["e"+type+fn] = fn;
obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});
}
}
function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'azScriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var dv = cel('div');
var gDiv = getEl('searchResults');
gDiv.innerHTML="";
var tmpItem = tmpData.Item
var ig = cel('img');
ig.setAttribute('src',tmpItem.thumburl);
ig.setAttribute('alt',tmpItem.title);
ig.style.cssText = "border:0px;height:"+tmpItem.thumbdims[0]+"px;width:"+tmpItem.thumbdims[1]+"px";
var a = cel('a');
a.setAttribute('href',tmpItem.url);
a.appendChild(ig);
var dv2 = cel('div');
dv2.style.cssText = "text-align:center;";
dv2.appendChild(a);
gDiv.appendChild(dv2);
var a = cel('a');
a.setAttribute('href',tmpItem.url);
a.appendChild(ctn(tmpItem.title));
dv.appendChild(a);
if(tmpItem.price)
{
dv.appendChild(ctn(tmpItem.price));
}
else if(tmpItem.lowestnewprice)
{
// ADDED CLASSNAME HERE
var eItem = tmpItem.lowestnewprice;
eItem.className = "price";
dv.appendChild(ctn(" - " + eItem));
}
else if(tmpItem.lowestusedprice)
{
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
gDiv.appendChild(dv);
if(tmpItem.desc){
tmpItem.desc = tmpItem.desc.replace(/<.*?>/gi,'');
tmpItem.desc = tmpItem.desc.replace(/&.*?;/gi,' ');
if(tmpItem.desc.length>121)
{
tmpItem.desc=tmpItem.desc.substr(0,120)+"..."
}
// ADDED CLASSNAME HERE
gDiv.appendChild(cel('br'));
var DItem = tmpItem.desc;
DItem.className = "price";
gDiv.appendChild(ctn(DItem));
}
}
}
var amazonSearch = function(){
var request = 'http://webservices.amazon.co.uk/onca/xml?Service=AWSECommerceService&SubscriptionId=19267494ZR5A8E2CGPR2&AssociateTag=mikita18v-21&Operation=ItemLookup&Style=http://www.virtualmedia.ie/json/ajsonSingleAsin.xsl&ContentType=text/javascript&IdType=ASIN&ItemId=' + gbAmazonAsin + '&ResponseGroup=Medium,ItemAttributes,OfferFull&CallBack=amzJSONCallback';
aObj = new JSONscriptRequest(request);
aObj.buildScriptTag();
aObj.addScriptTag();
}
var gbAmazonAsin = "<?php echo $productcode; ?>";
addEvent(window,"load",amazonSearch);

Categories

Resources