I am trying to create a slide show with images published from excel. The images work just fine when opening straight from the file. The images do not work when navigating to http://localhost nor browsing from IIS settings. Please see the code below. I have been at this for hours now and cant seem to find a fix.
<html>
<head>
<title>SHL Dashboard</title>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta http-equiv="refresh" content="35;url=default.html">
<style>
/* Change body background-color to change fade out color. */
body.siteshow { margin:0; padding:0; background-color:#FFFFFF; }
#menu
{
font-family:Arial;
font-size:9pt;
display:none;
opacity:0.00;
-mozopacity:0.00;
filter:alpha(opacity=0);
position:absolute;
top:10px;
left:10px;
padding:5px;
background-color:#000000;
color:#FFFFFF;
border:3px dotted #999999;
}
#menu a { color:#ffffff; }
#menu a:hover { text-decoration:none; }
#title { font-size:11pt; font-weight:bold; letter-spacing:2; }
#slides { font-size:9pt; line-height:16pt; }
.button { width:60px; font-size:9pt; letter-spacing:1; }
</style>
<script type="text/javascript">
var current_idx = 0;
var slides = new Array();
var menuwin;
var show_timer;
var menu_timer;
var menu;
var content;
var loaded = true;
// Define your "slides". 3 values for each are:
// 1. Duration in seconds.
// 2. Title to be used in menu.
// 3. Source URL. Can be full URI or a relative URL.
slides[1] = new Array(5, "Announcement 1", "C:/Website/shldash.com/wwwroot/Announcement_1.htm");
slides[2] = new Array(5, "Announcement 2", "C:/Website/shldash.com/wwwroot/Announcement_2.htm");
slides[3] = new Array(5, "Announcement 3", "C:/Website/shldash.com/wwwroot/Announcement_3.htm");
slides[4] = new Array(5, "Announcement 4", "C:/Website/shldash.com/wwwroot/Announcement_4.htm");
slides[5] = new Array(5, "Cust and Vis info", "C:/Website/shldash.com/wwwroot/Cust%20and%20Vis%20Info.htm");
slides[6] = new Array(5, "SHL Logo", "C:/Website/shldash.com/wwwroot/Dash_Logo.htm");
slides[7] = new Array(5, "Job info", "C:/Website/shldash.com/wwwroot/Job%20Openings.htm");
function xMenuInit()
{
var html = "";
for(idx=1; idx<slides.length; idx++) {
html += '<a href="javascript:Navigate('+idx+')">' +
slides[idx][1] + "</a><br />\n";
}
document.getElementById("slides").innerHTML = html;
menu.style.display = "block";
}
function xMenuShow()
{
clearTimeout(menu_timer);
opacity('menu', 0, 90, 500);
menu_timer = setTimeout("MenuHide()", 3500);
}
function MenuHide()
{
opacity('menu', 90, 0, 500);
}
function Pause()
{
clearTimeout(show_timer);
document.getElementById('play').style.display = "block";
document.getElementById('pause').style.display = "none";
}
function Navigate(slide_idx)
{
clearTimeout(show_timer);
if (current_idx == 0) {
if (!slide_idx) { slide_idx = 1; }
current_idx = slide_idx;
content.src = slides[current_idx][2];
document.getElementById('play').style.display = "none";
document.getElementById('pause').style.display = "block";
show_timer = setTimeout("Navigate()", slides[current_idx][0]*1000);
return;
}
if (slide_idx) {
current_idx = slide_idx;
content.src = slides[current_idx][2];
document.getElementById('play').style.display = "block";
document.getElementById('pause').style.display = "none";
return;
}
loaded = false;
current_idx++;
if ( current_idx == slides.length) { current_idx = 1; }
opacity('content', 100, 0, 500);
document.getElementById('play').style.display = "none";
document.getElementById('pause').style.display = "block";
show_timer = setTimeout("Navigate()", slides[current_idx][0]*1000);
return;
}
function opacity(id, opacStart, opacEnd, millisec)
{
//speed for each frame
var speed = Math.round(millisec / 100);
var timer = 0;
//determine the direction for the blending, if start and end are the same nothing happens
if(opacStart > opacEnd) {
for(i = opacStart; i >= opacEnd; i--) {
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
if (opacEnd == 0) { setTimeout("FadeOutTrigger('"+id+"')",((timer-1) * speed));; }
//if (opacEnd == 0) { FadeOutTrigger(id); }
} else if(opacStart < opacEnd) {
if (opacStart == 0) { FadeInTrigger(id); }
for(i = opacStart; i <= opacEnd; i++)
{
setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
timer++;
}
}
}
//change the opacity for different browsers
function changeOpac(opacity, id)
{
var object = document.getElementById(id).style;
object.opacity = (opacity / 100);
object.MozOpacity = (opacity / 100);
object.KhtmlOpacity = (opacity / 100);
object.filter = "alpha(opacity=" + opacity + ")";
}
function FadeOutTrigger(id)
{
//alert('FadeOut: '+id);
switch(id) {
case "menu":
document.getElementById(id).style.display = "none";
break;
case "content":
content.src = slides[current_idx][2];
//setTimeout("opacity('content', 0, 100, 500)", 1000);
break;
default:
break;
}
}
function FadeInTrigger(id)
{
//alert('FadeIn: '+id);
switch(id) {
case "menu":
document.getElementById(id).style.display = "block";
break;
case "content":
//opacity('content', 0, 100, 500);
break;
default:
break;
}
}
function FadeInContent()
{
if (!loaded) {
opacity('content', 0, 100, 500);
loaded = true;
}
}
function LoadTrigger()
{
//self.resizeTo(1366,768);
menu = document.getElementById('menu');
content = document.getElementById('content');
Navigate();
MenuInit();
MenuShow();
}
window.onload = LoadTrigger;
</script>
</head>
<body class="siteshow">
<iframe id="content" name="content" style="width:100%; height:100%;" frameborder="no" scrolling="auto" src="" onmouseover="MenuShow();" onload="FadeInContent();" ></iframe>
<div id="menu">
<div id="title">SiteShow Menu</div>
<div id="slides">
</div>
<p>
<input id="pause" class="button" style="display:block;" type="button" value="pause" onclick="Pause()" />
<input id="play" class="button" style="display:none;" type="button" value="play" onclick="Navigate()" />
</p>
</div>
</body>
</html>
A webpage has no access to your local filesystem. Don't use absolute URLs, use root-relative URLs.
That's how your slides should probably look like. btw. Arrays in JS start with the index 0 not 1.
var slides = [
[5, "Announcement 1", "/Announcement_1.htm"],
[5, "Announcement 2", "/Announcement_2.htm"],
[5, "Announcement 3", "/Announcement_3.htm"],
[5, "Announcement 4", "/Announcement_4.htm"],
[5, "Cust and Vis info", "/Cust%20and%20Vis%20Info.htm"],
[5, "SHL Logo", "/Dash_Logo.htm"],
[5, "Job info", "/Job%20Openings.htm"]
];
Then, please declare the variables that you use for(let idx=0; ....
don't use setTimeout("MenuHide()", 3500); with strings. They need to be eval'd and eval is evil. Pass a function: setTimeout(MenuHide, 3500);
KhtmlOpacity and filter = "alpha(opacity=...? How far downwards compatable do you want to stay? These were used for Safari 1.x and IE 5-9.
Related
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!
I am trying to get my cards to display 2 different boxes for the cards. If I hover just right with inspector I can see both cards are there, but I am having difficulty separating the two side by side. I am mostly trying to follow a tutorial but it has you do a lot of the work on your own, and I don't want to advance until I have this completely ready for the next task it gives me. Any help is greatly appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
War Cards!
</title>
<style>
.icard
{
position: absolute;
padding: 10px;
height: 200px;
width: 150px;
border: 1px solid black;
border-radius: 15px;
background-color: white;
display: inline-block;
top: 0;
left: 0;
}
.hand
{
position: relative;
}
.players
{
float: left;
width: 49%;
min-height: 300px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="start"></div>
<div id="message"></div>
<div id="board">
<div id="player1" class="players">
<div class="score"></div>
<div class="hand"></div>
</div>
<div id="player2">
<div class="score"></div>
<div class="hand"></div>
</div>
</div>
<div id="action">
<button id="btnBattle" type="button" class="btn">
Fight!
</button>
</div>
</div>
<script src="js/jquery-3.3.1.min.js">
</script>
<script>
$('document').ready(function() {
var suits = ["spades", "hearts", "clubs", "diams"];
var cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
var cards = [];
var players = [[], []];
var firstRun = true;
var gameOver = false;
var fightButton = document.querySelector("#btnBattle");
var p1 = document.querySelector('#player1 .hand');
var p2 = document.querySelector('#player2 .hand');
fightButton.addEventListener('click', battle);
function battle()
{
if (firstRun)
{
firstRun = false;
buildCards();
shuffleArray(cards);
dealCards(cards);
}
attack();
console.log('Works');
}
function attack()
{
if(!gameOver)
{
var card1 = players[0].shift();
var card2 = players[1].shift();
var pot = [card1, card2]
p1.innerHTML = showCard(card1, 0);
p2.innerHTML = showCard(card2, 0)
// Check Winners
// Update Scores
}
}
function showCard(c, p)
{
var move = p * 40;
var bgColor = (c.icon == 'H' || c.icon == 'D') ? 'red' : 'black';
var bCard = '<div class="icard" style="color:'+ bgColor +'">' + c.num + ' &' + c.suit + ';</div>';
console.log(c, move);
return bCard;
}
function buildCards()
{
cards = [];
for (s in suits)
{
var suitNew = suits[s][0].toUpperCase();
for(n in cardFace)
{
var card = {
suit:suits[s],
num:cardFace[n],
cardValue:parseInt(n) +2,
icon:suitNew
}
cards.push(card);
}
}
console.log(cards);
}
function dealCards(array)
{
for(var i = 0; i < array.length; i++)
{
// swaps between remainder 0 and 1, which signifies player[0 OR 1], and then pushes that onto parameter,(array), which
// is cards which is an array, at the index of for loop [i]
var m = i % 2;
players[m].push(array[i])
}
console.log(players)
}
//
// function dealCards(array)
// {
// for(var i = 0; i < array.length; i++)
// {
// if(i % 2 === 0 )
// {
// players[0].push(array[i]);
// }
// else
// {
// players[1].push(array[i]);
// }
//
// }
// console.log(players);
// }
//
function shuffleArray(array)
{
for(var x = array.length -1; x > 0; x--)
{
var ii = Math.floor(Math.random() * (x + 1))
var temp = array[x];
array[x] = array[ii];
array[ii] = temp;
}
console.log(cards);
return array;
}
});
</script>
</body>
</html>
I think you missed to add the players class to the player 2 element.
<div id="player2" class="players">
https://jsfiddle.net/zkw9s4an/
Add css to the player 2 div to move it margin left by the amount you need.
#player2
{
margin-left:10%;
}
Refer this.
I think this is working but not really. I also don't think that it is the best approach.
The timer serves as another function running while having the ability to change the pulsing rate of the image.
I have tried to use gifs instead of because they have different speeds, there isn't a smooth transition when switching between images.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<style>
#red-square {
position: absolute;
display: inline-block;
z-index: 1;
top : 200px;
right: 200px;
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="result"></div>
<div id="red-square"></div>
<button onclick="speedOne();">speed one</button>
<button onclick="speedTwo();">speed two</button>
<button onclick="speedThree();">speed three</button>
<script>
var counter = 0,
stopTimeoutTwo = null,
stopTimeoutThree = null,
currentSpeed = "speed one";
function runCounter() {
counter++;
result.textContent = counter;
if(currentSpeed == "speed one") {
if((counter%60) == 0) {
$("#red-square").hide();
}else if((counter%60) != 0) {
$("#red-square").show();
}
}
else if(currentSpeed = "speed two") {
if((counter%45) == 0) {
$("#red-square").hide();
}else if((counter % 45) != 0) {
$("#red-square").show();
}
}else if(currentSpeed = "speed three") {
if((counter%30) == 0) {
$("#red-square").hide();
}else if((counter%30) != 0) {
$("#red-square").show();
}
}
if(counter < 1e5) timer = setTimeout(runCounter, 0);
}
runCounter();
function stepOne() {
currentSpeed = "speed one";
}
function stepTwo() {
currentSpeed = "speed two";
}
function stepThree() {
currentSpeed = "speed three";
}
</script>
</body>
</html>
You can use setInterval to create your efect like so: Fiddle!
This is the JS I used:
var speed = 4000;
var inter;
var square = document.getElementById("red-square");
square.style.backgroundColor = "red";
function myTime(){
inter = setInterval(function(){
console.log(square.style.backgroundColor+" "+speed);
if(square.style.backgroundColor == "red"){
square.style.backgroundColor = "blue";
}
else{
square.style.backgroundColor = "red";
}
}, speed);
}
function changSpeed(s){
clearInterval(inter);
speed = s;
inter=null;
myTime();
}
myTime();
the rest is your code.
I'm trying to learn Javascript and at the moment and I am working on AddEventListener.
What I'm trying to do is to add a new row and so far it works.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.colorOrange {
background-color: orange;
}
.colorBlue {
background-color: blue;
}
.colorYellow {
background-color: yellow;
}
.colorGray {
background-color: gray;
}
.colorRed {
background-color: red;
}
.colorGreen {
background-color: green;
}
.colorWhite {
background-color: white;
}
#main {
margin: 0 auto;
width: 325px;
text-align: center;
background-color: gray;
}
.row {
width: 300px;
padding: 10px;
border: 1px solid black;
display: block;
}
.hideButton, .mainText, .deleteButton {
margin: 0 auto;
padding: 10px;
border: 1px solid black;
display: inline;
}
.btn {
}
</style>
</head>
<body>
<div id="main">
<div class="AddBtn btn">Add</div>
<input type="text" id="txtBox" name="text till ruta" />
</div>
<script>
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
So far everything works as I want it to do. But when I click on "<" it will go in to this function and find all tags with the hideButton class in it.
The first click it won't find anything, but the second time it will find the "<" value and an alert window will popup and show the value. Here is where I
get lost and can't get it to work. When you click the the third time it will
loop or whatever to call it - anyway it will show the alert window 2 times and
then if you repeat the same click it will do the same thing 3 times and so it goes.
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
for (var j = 0; j < hideButton.length; j++) {
hideBtn = hideButton[j];
hideBtn.addEventListener('click', function () {
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}, false);
}
}
}, false);
}
}
window.onload = addListeners;
</script>
</body>
</html>
The goal with this exercise is that
when you click add button add the text from the input field and add that text to the new row.
and "<" shall hide the row and change it to ">" to show it again
and "X" shall just delete the row.
But what I need help with is finding the value part that I mentioned above.
Here is my rework of your javascript. I explained my solution in your comment, but it may be a bit more clear if illustrated.
In the addListeners function, I removed the hideOrShow call as it shouldn't be called in the add button.
Next, I removed the for loop in the hideOrShow method as you really are only after the caller. I also removed the addEventListener call in the same method as you already have an event listener on that element, so there's no need to add one again.
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
//hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}
}, false);
}
}
window.onload = addListeners;
I have an image multi-uploader script which also each item uploaded was preview 1st before it submitted and each images has its following textarea which are also generated by JavaScript. I want to use the tinymce editor to each textarea generated by the ajax.
Here is my script:
function fileQueueError(file, errorCode, message) {
try {
var imageName = "error.gif";
var errorName = "";
if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
errorName = "You have attempted to queue too many files.";
}
if (errorName !== "") {
alert(errorName);
return;
}
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
imageName = "zerobyte.gif";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
imageName = "toobig.gif";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex) {
this.debug(ex);
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (numFilesQueued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function uploadProgress(file, bytesLoaded) {
try {
var percent = Math.ceil((bytesLoaded / file.size) * 100);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setProgress(percent);
if (percent === 100) {
progress.setStatus("Creating thumbnail...");
progress.toggleCancel(false, this);
} else {
progress.setStatus("Uploading...");
progress.toggleCancel(true, this);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.upload_target);
if (serverData.substring(0, 7) === "FILEID:") {
addRow("tableID","thumbnail.php?id=" + serverData.substring(7),file.name);
//setup();
//generateTinyMCE('itemdescription[]');
progress.setStatus("Thumbnail Created.");
progress.toggleCancel(false);
} else {
addImage("images/error.gif");
progress.setStatus("Error.");
progress.toggleCancel(false);
alert(serverData);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadComplete(file) {
try {
/* I want the next upload to continue automatically so I'll call startUpload here */
if (this.getStats().files_queued > 0) {
this.startUpload();
} else {
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setComplete();
progress.setStatus("All images received.");
progress.toggleCancel(false);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadError(file, errorCode, message) {
var imageName = "error.gif";
var progress;
try {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Cancelled");
progress.toggleCancel(false);
}
catch (ex1) {
this.debug(ex1);
}
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Stopped");
progress.toggleCancel(true);
}
catch (ex2) {
this.debug(ex2);
}
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
imageName = "uploadlimit.gif";
break;
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex3) {
this.debug(ex3);
}
}
function addRow(tableID,src,filename)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
rowCount + 1;
row.id = "row"+rowCount;
var cell0 = row.insertCell(0);
cell0.innerHTML = rowCount;
cell0.style.background = "#FFFFFF";
var cell1 = row.insertCell(1);
cell1.align = "center";
cell1.style.background = "#FFFFFF";
var imahe = document.createElement("img");
imahe.setAttribute("src",src);
var hidden = document.createElement("input");
hidden.setAttribute("type","hidden");
hidden.setAttribute("name","filename[]");
hidden.setAttribute("value",filename);
/*var hidden2 = document.createElement("input");
hidden2.setAttribute("type","hidden");
hidden2.setAttribute("name","filename[]");
hidden2.setAttribute("value",filename);
cell1.appendChild(hidden2);*/
cell1.appendChild(hidden);
cell1.appendChild(imahe);
var cell2 = row.insertCell(2);
cell2.align = "left";
cell2.valign = "top";
cell2.style.background = "#FFFFFF";
//tr1.appendChild(td1);
var div2 = document.createElement("div");
div2.style.padding ="0 0 0 10px";
div2.style.width = "400px";
var alink = document.createElement("a");
//alink.style.margin="40px 0 0 0";
alink.href ="#";
alink.innerHTML ="Cancel";
alink.onclick= function () {
document.getElementById(row.id).style.display='none';
document.getElementById(textfield.id).disabled='disabled';
};
var div = document.createElement("div");
div.style.margin="10px 0";
div.appendChild(alink);
var textfield = document.createElement("input");
textfield.id = "file"+rowCount;
textfield.type = "text";
textfield.name = "itemname[]";
textfield.style.margin = "10px 0";
textfield.style.width = "400px";
textfield.value = "Item Name";
textfield.onclick= function(){
//textfield.value="";
if(textfield.value=="Item Name")
textfield.value="";
if(desc.innerHTML=="")
desc.innerHTML ="Item Description";
if(price.value=="")
price.value="Item Price";
}
var desc = document.createElement("textarea");
desc.name = "itemdescription[]";
desc.cols = "80";
desc.rows = "4";
desc.innerHTML = "Item Description";
desc.onclick = function(){
if(desc.innerHTML== "Item Description")
desc.innerHTML = "";
if(textfield.value=="Item name" || textfield.value=="")
textfield.value="Item Name";
if(price.value=="")
price.value="Item Price";
}
var price = document.createElement("input");
price.id = "file"+rowCount;
price.type = "text";
price.name = "itemprice[]";
price.style.margin = "10px 0";
price.style.width = "400px";
price.value = "Item Price";
price.onclick= function(){
if(price.value=="Item Price")
price.value="";
if(desc.innerHTML=="")
desc.innerHTML ="Item Description";
if(textfield.value=="")
textfield.value="Item Name";
}
var span = document.createElement("span");
span.innerHTML = "View";
span.style.width = "auto";
span.style.padding = "10px 0";
var view = document.createElement("input");
view.id = "file"+rowCount;
view.type = "checkbox";
view.name = "publicview[]";
view.value = "y";
view.checked = "checked";
var div3 = document.createElement("div");
div3.appendChild(span);
div3.appendChild(view);
var div4 = document.createElement("div");
div4.style.padding = "10px 0";
var span2 = document.createElement("span");
span2.innerHTML = "Default Display";
span2.style.width = "auto";
span2.style.padding = "10px 0";
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "setdefault";
radio.value = "y";
div4.appendChild(span2);
div4.appendChild(radio);
div2.appendChild(div);
//div2.appendChild(label);
//div2.appendChild(table);
div2.appendChild(textfield);
div2.appendChild(desc);
div2.appendChild(price);
div2.appendChild(div3);
div2.appendChild(div4);
cell2.appendChild(div2);
}
function addImage(src,val_id) {
var newImg = document.createElement("img");
newImg.style.margin = "5px 50px 5px 5px";
newImg.style.display= "inline";
newImg.id=val_id;
document.getElementById("thumbnails").appendChild(newImg);
if (newImg.filters) {
try {
newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
}
} else {
newImg.style.opacity = 0;
}
newImg.onload = function () {
fadeIn(newImg, 0);
};
newImg.src = src;
}
function fadeIn(element, opacity) {
var reduceOpacityBy = 5;
var rate = 30; // 15 fps
if (opacity < 100) {
opacity += reduceOpacityBy;
if (opacity > 100) {
opacity = 100;
}
if (element.filters) {
try {
element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
}
} else {
element.style.opacity = opacity / 100;
}
}
if (opacity < 100) {
setTimeout(function () {
fadeIn(element, opacity);
}, rate);
}
}
/* ******************************************
* FileProgress Object
* Control object for displaying file info
* ****************************************** */
function FileProgress(file, targetID) {
this.fileProgressID = "divFileProgress";
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
fadeIn(this.fileProgressWrapper, 0);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
}
this.height = this.fileProgressWrapper.offsetHeight;
}
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "progressContainer blue";
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfuploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfuploadInstance.cancelUpload(fileID);
return false;
};
}
};
I am using a swfuploader and I just added a input fields and a textarea when it preview the images which ready to be uploaded.
And from my HTML I have this script:
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "../we_modules/upload.php", // Relative to the SWF file or absolute
post_params: {"PHPSESSID": "<?php echo session_id(); ?>"},
// File Upload Settings
file_size_limit : "20 MB", // 2MB
file_types : "*.*",
//file_types : "",
file_types_description : "jpg",
file_upload_limit : "0",
file_queue_limit : "0",
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
//file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "../we_modules/images/SmallSpyGlassWithTransperancy_17x18.png", // Relative to the SWF file
button_placeholder_id : "spanButtonPlaceholder",
button_width: 180,
button_height: 18,
button_text : '<span class="button">Select Files<span class="buttonSmall">(2 MB Max)</span></span>',
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt;cursor:pointer } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 0,
button_text_left_padding: 18,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
// Flash Settings
flash_url : "../swfupload/swfupload.swf",
custom_settings : {
upload_target : "divFileProgressContainer"
},
// Debug Settings
debug: false
});
};
</script>
Where should I put on the tinymce function as you mention below?
Taken directly from the TinyMCE documentation:
<script type="text/javascript" src="<your installation path>/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form method="post" action="somepage">
<textarea name="content" style="width:100%">
</textarea>
</form>
Please read the documentation for basic questions like this.
If you get stuck or need help after you've done that, provide a clear explanation of your problem (and sample code if possible) so that we can help you.
Edit:
Alright, I've attempted a solution to the problem. The following code loads 20 images and textareas dynamically and then turns the textareas into TinyMCE editors (I hope you don't mind the jQuery):
<html>
<head>
<script src="TinyMCE/jscripts/tiny_mce/tiny_mce.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
img { height: 100px; display: block;}
li { border: 1px solid black; margin: 1em; padding: 1em; }
#message { position: fixed; top: 0; left: 50%; margin-left: -100px; width: 200px; text-align: center; background-color: white; border: 1px solid black;}
</style>
</head>
<body>
<ul>
</ul>
<div id="message">Loading...</div>
<script>
$(function(){
var numImages = 20;
for (var i = 0; i < numImages; i++) {
// Create an img element with a random image
var img = $('<img />').attr('src', randomXKCD);
// Attach a callback to the image's load event
img.load(function(){
numImages--;
if (numImages === 0) {
// When all the images have loaded,
// turn the textareas into tinyMCE editors
tinyMCE.init({
mode: 'textareas',
theme: 'simple',
oninit: function(){$('#message').hide()}
});
}
});
// Add the image and a textarea to the document.
$('ul').append(
$('<li />')
.append(img)
.append('<textarea />')
);
}
// helper function to get a random image.
function randomXKCD() {
var xkcds = [
'http://imgs.xkcd.com/comics/barrel_mommies.jpg',
'http://imgs.xkcd.com/comics/su_doku.jpg',
'http://imgs.xkcd.com/comics/linux_user_at_best_buy.png',
'http://imgs.xkcd.com/comics/commented.png',
'http://imgs.xkcd.com/comics/typewriter.png',
'http://imgs.xkcd.com/comics/pirate_bay.png',
'http://imgs.xkcd.com/comics/quirky_girls.png',
'http://imgs.xkcd.com/comics/firefly.jpg',
'http://imgs.xkcd.com/comics/kepler.jpg',
'http://imgs.xkcd.com/comics/centrifugal_force.png',
'http://imgs.xkcd.com/comics/trebuchet.png',
'http://imgs.xkcd.com/comics/egg_drop_failure.png',
'http://imgs.xkcd.com/comics/too_old_for_this_shit.png',
'http://imgs.xkcd.com/comics/2008_christmas_special.png',
'http://imgs.xkcd.com/comics/braille.png',
'http://imgs.xkcd.com/comics/impostor.png',
'http://imgs.xkcd.com/comics/not_enough_work.png'
];
return xkcds[Math.floor(Math.random() * xkcds.length)];
}
});
</script>
</body>
</html>