Colorpicker in javascript - javascript

Im currently making a simple color picker for school. Well it should be simple, however my programming in Javascript is really bad. It contains an array with the names, and a array with the codes. The codes will only contain 00, 33, 66, 99, ff, cc and the code is only 6 chars long as some of you know. With a loop i manage to print everything on screen, but now i want to make the background color the same color as the one im clicking. And i want the code of the one that im clicking in a textbox.
So heres my code:
DHTML with jQuery: Opdracht 4
<script type="text/javascript">
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
"dark faded blue", // #000099
);
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color + ' ' + colorNames[count] + '" onclick="'+source+' (\''+color+'\',\''+colorNames[count]+'\')"></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<input type="text" id="color"/>
</body>
</html>
I tried a line in the onclick button, but i realised that wont work. Do you guys have any suggestions? And sorry if it looks a little messy, as I said I am a real nub in javascript.
EDIT:
Working code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DHTML with jQuery: Opdracht 4</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function changeBg(color){
var currentColor = $('#printColor').val();
$('#input').css('background', currentColor);
}
function printColor(color) {
$('#printColor').val(color);
$("#input").on("click", function() {
$(this).css("background", "printColor");
});
}
function changeFG() {
var currentColor = $('#printColor').val();
$('#input').css('color', currentColor);
}
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
);
var count = 0;
document.writeln('<table width="800" height="300">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#' + color + '" title="#' + color + ' ' + colorNames[count] + '" onclick="javascript:printColor(\'#'+color+'\')" ' + source + '(\'' + color + '\',\'' + colorNames[count] + '\')"></td>');
count++;
var source = function(color){
document.body.style.background = "#" + color;
}
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<div id="input">
<input type="text" id="printColor" name="printColor" />
Change Background / Foreground color!
<p> Lorem ipsum blablabla</p>
</div>
</body>
</html>

Without making too much changes to your code I think this is what you want.
I just changed your array into an object so that you can map the hex code of the color to the name and declared the changeBg function. Just fill in the rest of the colors.
<body>
<script type="text/javascript">
(function(){
var colorNames = {
"000000": "black",
"000033": "weak blue",
"000066": "obsure dull blue",
"000099": "dark faded blue"
//...rest of colors
};
window.changeBg = function(color){
document.body.style.background = "#" + color;
document.getElementById("color").value = colorNames[color];
}
var showPicker = function(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color +'" onclick=changeBg(\''+color+'\')></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker();
})();
</script>
<input type="text" id="color" readonly = true/>
</body>

Related

How to insert resulting value of randomizer into html input value? (JavaScript)

I'm working on a background-gradient generator that can be manipulated by either selecting one of two HTML color inputs and choosing color manually (which is then displayed live in the background) or by clicking a "randomize" button and generating two random rgb colors to be displayed.
Github repository here.
The problem is, when you click "randomize", the value of the color input fields remains the same while the background changes. I want to make it so that the values of each random rgb color generated are then added to the inner html "value" of the input boxes so that the boxes display exactly what two colors were selected. I'm having trouble figuring out the logic of doing this.
Here is the JS of the color randomizer function if that helps:
function randomRGB() {
var rgbValues = [];
for(var i = 0; i < 3; i++) {
rgbValues.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')';
}
function setRandom() {
body.style.background = 'linear-gradient(to right, ' + randomRGB() + ', ' + randomRGB() + ')';
css.textContent = body.style.background + ';';
}
And here is the HTML:
<!doctype html>
<html lang="en">
<head>
<title>Gradient Background</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body id = "gradient">
<div class="container">
<h1>Background Generator</h1>
<div class="inputs">
<input class = "color1" type="color" name="color1" value="#B5DDFF">
<input class = "color2" type="color" name="color2" value="#D998FF" id=""><br>
</div>
<button class="random">Randomize</button>
<h2>Current CSS Background</h2>
<h3></h3>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>
Please let me know if there's anything I can clarify, I'm definitely a beginner when it comes to JS and I may not have explained it in the best way.
Considering that your inputs are under a .inputs container, as I see in your github repository:
function setRandom() {
const firstRndRGB = randomRGB();
const secondRndRGB = randomRGB();
const inputs = document.getElementsByClassName('inputs');
inputs[0].value = firstRndRGB;
inputs[1].value = secondRndRGB;
body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')';
css.textContent = body.style.background + ';';
}
EDIT:
As it has to be insterted into a type="color" input, which only accepts Hex formatted colors, we must also convert the RGB format into a Hex format using regex like this:
function getHexFromRGB(x){
return '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');
}
And then just do
inputs[0].value = getHexFromRGB(firstRndRGB);
inputs[1].value = getHexFromRGB(secondRndRGB);
So all you need is to use those rbg strings and convert them into hex format so you can assign them to each input's value
function randomRGB() {
var rgbValues = [];
for(var i = 0; i < 3; i++) {
rgbValues.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')';
}
function setRandom() {
const firstRndRGB = randomRGB();
const secondRndRGB = randomRGB();
const inputs = document.querySelectorAll('.inputs input');
inputs[0].value = toHEX(firstRndRGB);
inputs[1].value = toHEX(secondRndRGB);
document.body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')';
//css.textContent = body.style.background + ';';
}
function toHEX(rgbString){
rgbString = rgbString.split("(")[1].split(")")[0];
rgbString = rgbString.split(",");
rgbString = rgbString.map(x => {
x = parseInt(x).toString(16);
return (x.length==1) ? "0"+x : x;
});
rgbString = "#"+rgbString.join("");
return rgbString;
}
setRandom();
document.getElementById('randomize').addEventListener('click', ()=>{
setRandom()
});
<body id = "gradient">
<div class="container">
<h1>Background Generator</h1>
<div class="inputs">
<input class = "color1" type="color" name="color1">
<input class = "color2" type="color" name="color2" id=""><br>
</div>
<button id='randomize' class="random">Randomize</button>
<h2>Current CSS Background</h2>
<h3></h3>
</div>
</body>
MDN says that the input type="color" takes a value in lower-case hexadecimal notation. In the view there must be printed rgb value. Rename randomRGB() with randomColor() and return both of them.
function randomColor() {
var rgb = [];
var hex = [];
for (var i = 0; i < 3; i++) {
var randomColorPart = Math.floor(Math.random() * 256);
var randomColorPartHEX = randomColorPart.toString(16);
if (randomColorPartHEX.length < 2) {
randomColorPartHEX = '0' + randomColorPartHEX;
}
rgb.push(randomColorPart);
hex.push(randomColorPartHEX);
}
return {
'rgb': 'rgb(' + rgb.join() + ')',
'hex': '#' + hex.join(''),
}
}
function setRandom() {
var randomColor1 = randomColor();
var randomColor2 = randomColor();
var bgLinearGradient = 'linear-gradient(to right, ' + randomColor1.rgb + ', ' + randomColor2.rgb + ')';
body.style.background = bgLinearGradient;
css.textContent = bgLinearGradient+ ';';
color1.value = randomColor1.hex;
color2.value = randomColor2.hex;
}

Scope model update

Below demo app is showing three different progressbars.
Now user needs to select which progressbar he/she wants to change value
and then on button click which is provided at same page.
var app = angular.module('myApp',[]);
app.component('listComponent', {
template:'<div ng-repeat="progress in $ctrl.obj.bars track by $index">' +
'<progress value="{{progress}}" max="{{$ctrl.obj.limit}}">{{progress}}</progress><br>'+
'</div>'+
'<br>' +
'<div>' +
'Selected Progressbar : {{$ctrl.selectedProgressbar}}' +
'<span>' +
'<select name="selectedProgressbar" ng-model="$ctrl.selectedProgressbar">' +
'<option ng-repeat="progress in $ctrl.obj.bars track by $index" value="{{$index}}">{{progress}}</option>' +
'</select>' +
'</span>' +
'<span ng-repeat="btn in $ctrl.obj.buttons">' +
'<button class="btn" ng-click="$ctrl.changeProgress(btn, $ctrl.selectedProgressbar)">{{btn}}</button>' +
'</span>' +
'</div>',
controller: function () {
this.obj = {
"buttons": [
10,
38,
-13,
-18
],
"bars": [
62,
45,
62
],
"limit": 230
};
function changeProgressbar(val){
var val = parseInt(val);
var barValue = this.obj.bars[this.selectedProgressbar];
var selectedBar = this.selectedProgressbar;
var bars = this.obj.bars;
// this.obj.bars[0] = parseInt(this.obj.bars[0]) + parseInt(val);
// if we remove comment from above code and comment below one then progresbar value changes at same time
// but with below code its not changing at same time its changing when we click on any button or change progreebar selection
if(val > 0){
var total = parseInt(barValue) + val;
var update = setInterval(function() {
if (parseInt(barValue) > total) {
clearInterval(update);
}
barValue = parseInt(barValue) + 1;
bars[selectedBar] = barValue;
}, 15);
}
}
this.changeProgress = changeProgressbar;
}
});
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="This is just demo application by using Angular 1.6">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Progressbar in Angular 1.6</title>
<style type="text/css" media="screen">
progress:after {
display: block;
content: attr(value);
text-align:center;
}
</style>
</head>
<body ng-app="myApp">
<list-component></list-component>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script>
</script>
</body>
</html>
jsBin is here,
now after selecting any progressbar then click on any first two buttons then no change is found on progreebar
but as soon as you click again or select some other progressbar then value is changing.
After going through your code, I found some issues there.
You should change the changeProgressbar function and remove the interval function.
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[add your bin description]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Progressbar in Angular 1.6</title>
<style type="text/css" media="screen">
progress:after {
display: block;
content: attr(value);
text-align:center;
}
</style>
</head>
<body ng-app="myApp">
<list-component></list-component>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.component('listComponent', {
// isolated scope binding
template:'{{$ctrl.obj.bars}}<div ng-repeat="progress in $ctrl.obj.bars track by $index">' +
'<progress value="{{progress}}" max="{{$ctrl.obj.limit}}">{{progress}}</progress><br>'+
'</div>'+
'<br>' +
'<div>' +
'Selected Progressbar : {{$ctrl.selectedProgressbar}}' +
'<span>' +
'<select name="selectedProgressbar" ng-model="$ctrl.selectedProgressbar">' +
'<option ng-repeat="progress in $ctrl.obj.bars track by $index" value="{{$index}}">{{progress}}</option>' +
'</select>' +
'</span>' +
'<span ng-repeat="btn in $ctrl.obj.buttons">' +
'<button class="btn" ng-click="$ctrl.changeProgress(btn, $ctrl.selectedProgressbar)">{{btn}}</button>' +
'</span>' +
'</div>',
controller: function () {
this.obj = {
"buttons": [
10,
38,
-13,
-18
],
"bars": [
62,
45,
62
],
"limit": 230
};
function changeProgressbar(val){
var val = parseInt(val);
var barValue = this.obj.bars[this.selectedProgressbar];
var selectedBar = this.selectedProgressbar;
var bars = this.obj.bars;
// this.obj.bars[0] = parseInt(this.obj.bars[0]) + parseInt(val);
// if we remove comment from above code and comment below one then progresbar value changes at same time
// but with below code its not changing at same time its changing when we click on any button or change progreebar selection
if(val > 0){
var total = parseInt(barValue) + val;
if (parseInt(barValue) > total) {
clearInterval(update);
}
else
{
barValue = total;
bars[selectedBar] = barValue;
}
}
}
this.changeProgress = changeProgressbar;
}
});
</script>
</body>
</html>
PLEASE RUN THE ABOVE SNIPPET
Here is a working DEMO

Product colorize with a texture image (jquery)

I want to use product colorize from nikorablin but in his script use rgb colors and i want to use img (textures)
Here is the script
/*
* productColorizer - jQuery Plugin
* version: 1.2 October 2012
* #requires jQuery v1.6 or later
*
* Examples at http://nikorablin.com/sandbox/productColorizer/
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
*/
(function($){
$.fn.productColorizer = function(options) {
// defaults
var defaults = {
transparency: 0.55,
swatchTransparency: 0.75,
secondaryTransparency: 0.55,
swatchClass: '.swatch'
};
// extend defaults
var options = $.extend(defaults, options);
return this.each(function() {
// init objects
var o = options;
var obj = $(this);
var swatch = obj.find(o.swatchClass);
var swatches = obj.find(o.swatchClass + " a");
var mask = obj.find('.mask');
// set swatch colors with the rel values
$(swatches).each(function(){
var color = "rgba(" + $(this).attr('rel') + "," + o.swatchTransparency + ")";
$(this).html('<span>'+$(this).html()+'</span>');
$(this).find('span').css('background', color);
if($.browser.msie) {
color = $(this).attr('rel');
var colors = color.split(",");
color = "#" + colorToHex(colors);
$(this).find('span').css({'background-color': color});
}
});
// set background color of mask with rel values and transparency
$(swatches).click(function(e) {
e.preventDefault();
$(swatches).removeClass('active');
$(this).addClass('active');
var color = "rgba(" + $(this).attr('rel') + "," + o.transparency + ")";
var mask = $(this).attr('href');
if($(mask).attr('role')) {
$(mask).empty();
var R = Raphael(mask.substring(1), $(mask).width(), $(mask).height());
var style = {
fill: "rgb(" + $(this).attr('rel') + ")",
opacity: o.secondaryTransparency,
"stroke-width": 0
};
R.path($(mask).attr('role')).attr(style);
} else {
$(mask).css({"background-color": color}, 1000);
if($.browser.msie) {
color = $(this).attr('rel');
var colors = color.split(",");
color = colorToHex(colors);
$(mask).css({'background': 'transparent', 'zoom': 1, 'filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#80' + color + ',endColorstr=#80' + color + ')'});
}
}
});
// create tooltips showing color name on swatch hover
$(swatches).hover(function(e) {
e.preventDefault();
var offsetX = $(this).offset().left - $(this).parent().offset().left;
var offsetY = $(this).offset().top - $(this).parent().offset().top + 25;
var text = $(this).attr('title');
if(!$.browser.msie) $(this).removeAttr('title');
$(this).after('<div class="colorizer-tooltip"><div class="colorizer-pointer-up"><div class="colorizer-pointer-up-inner"></div></div><span class="colorizer-tooltip-text">' + text + '</span></div>');
var offsetToolTip = ($('.colorizer-tooltip').width()/2)-12;
$('.colorizer-tooltip').css({'left': offsetX-offsetToolTip, 'top':offsetY});
}, function() {
var text = $('.colorizer-tooltip-text').html();
$(this).attr('title', text);
$(".colorizer-tooltip").remove();
});
//rgb to hex
function colorToHex(color) {
var red = parseInt(color[0]);
var green = parseInt(color[1]);
var blue = parseInt(color[2]);
var rgb = blue | (green << 8) | (red << 16);
return rgb.toString(16);
};
});
}
})(jQuery);
and html
<a rel="255,211,8" href="#mask" title="Yellow">Yellow</a>
I want to use something like this
<a rel="http://www.ex.etc/img.jpg" href="#mask" title="ImgTexture">Img</a> (example how i want to use)
Or with <a rel="img_src" href="htttp://etc.etc/img.jpg" alt="#mask" title="imgtexture"></a>
I am newbie at propgraming .. how i have to change the jquery ?
Thx
Download archive with all js and css files.
Add them to you HTML page:
<html>
<head>
<title>Color</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="js/raphael-min.js"></script>
<script type="text/javascript" src="js/jquery.productColorizer.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.productColorizer.css" />
<script type="text/javascript">
$(document).ready(function(){
$('.product').productColorizer();
});
</script>
</head>
<body>
<div class="product">
<div class="swatch">
<a rel="32,223,95" href="#mask" title="Green">Green</a>
<a rel="255,211,8" href="#mask" title="Yellow">Yellow</a>
<a rel="255,101,8" href="#mask" title="Orange">Orange</a>
<a rel="16,200,255" href="#mask" title="Blue">Blue</a>
<a rel="142,8,255" href="#mask" title="Purple">Purple</a>
<a rel="245,25,45" href="#mask" title="Red">Red</a>
</div>
</div>
</body>
</html>
As shown here:
And you will see the result:

Google Earth API Draw many placemarks without crashing the browser

I am using google earth api and I want to draw multiple placemark (points and polygons) on the map at once. The actual scenario is that the user have a list of its and he can click them to draw them 1 by 1 or click the draw all button which will then start drawing about 3000 placemarks. The problem is after a few second the browser/plugin crashes or prompts the user to stop the plugin from executing.
This is an example code I made :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<head>
<title>Many Points Test!</title>
<script src="http://www.google.com/jsapi?key=ABQIAAAAwbkbZLyhsmTCWXbTcjbgbRSzHs7K5SvaUdm8ua-Xxy_-2dYwMxQMhnagaawTo7L1FE1-amhuQxIlXw"></script>
<script>
google.load("earth", "1");
var ge = null;
function init() {
google.earth.createInstance("map3d", initCallback, failureCallback);
}
function initCallback(object) {
ge = object;
ge.getWindow().setVisibility(true);
// Get the current view.
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Set new latitude and longitude values.
lookAt.setLatitude(37.802);
lookAt.setLongitude(-122.448425);
lookAt.setRange(1000);
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
addPoints(1);
}
function failureCallback(object) {
}
function addPoints(num) {
for(var i = 0; i < num; i++)
{
var x = "37.802" + i.toString();
var kmlString = ''
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2">'
+ '<Document>'
+ ' <Placemark>'
+ ' <name>Placemark from KML string</name>'
+ ' <Point>'
+ ' <coordinates>-122.448425,'+x+',0</coordinates>'
+ ' </Point>'
+ ' </Placemark>'
+ '</Document>'
+ '</kml>';
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
}
}
</script>
</head>
<body onload='init()' id='body'>
<center>
<div id='map3d' style='border: 1px solid silver; height: 600px; width: 800px;'></div>
<input onclick="addPoints(10000)" value="Add Many Points" type="button" />
</center>
</body>
</html>
Anyone know How I can keep the browser responsive or even load the placemarks in an asynchronous way?
What seemed to solve it was pausing between every placemark I drew using setTimeout :
function addPoints(arr, index) {
var end = Math.min(arr.length, index + 1);
for (var i = index; i < end; i++) {
var kmlObject = ge.parseKml(arr[i]);
ge.getFeatures().appendChild(kmlObject);
document.getElementById('done').innerHTML = i;
}
if (end != arr.length) {
setTimeout(function () {
addPoints(arr, end);
}, 1);
} else {
alert('done');
}
}
addPoints(arr, 0); /* Function Call */

JQuery Mobile collapsible does not apply to div

I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.
#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>

Categories

Resources