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!
Related
inside the squareGenerator() function I create a yellow square every 1000 milliseconds. But I want each square to fall from the top of the screen to the very bottom, I want to do this in the fallingFunction(), something like what you would see in the "Guitar Hero" video game, where the notes fall down. Thank you.
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": "yellow",
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('id', idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
//Square Falling
function fallingFunction() {
$("#" + idGenerated).css({"margin-top": "100px",});
}
var squareGenerationInterval = setInterval(fallingFunction, 1000);
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
This is easy, you can use JQuery Animate. Although the code does need to be customized in other places in order to work.
First, let's add a parameter to fallingFunction which is square.
function fallingFunction(square) {
square.animate(
// Styles
{"margin-top": "100px"},
// Speed in miliseconds
5000);
}
This basically just animates the margin-top to 100px.
Second, remove the interval that calls fallingFunction.
So delete var squareGenerationInterval = setInterval(fallingFunction, 1000);.
Now you'll have to edit your square ids because #0 is not accepted, try something like #square0.
newSquare.attr('id', 'square' + idGenerated);
And Finnaly, you can call fallingFunction after $('.father').append(newSquare); passing in the newSquare object. Call it like this: fallingFunction(newSquare);.
So this is how your code should look like:
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": "yellow",
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('id', 'square' + idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
fallingFunction(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
//Square Falling
function fallingFunction(sqaure) {
sqaure.animate(
// Styles
{"margin-top": "100px"},
// Speed in miliseconds
5000);
}
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
I used CSS keyframes and some additional CSS to achieve this.
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
// if (idGenerated < 5) return false;
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": idGenerated % 2 === 0 ? 'green' : 'blue',
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('class', 'sq'); // add class
newSquare.attr('id', idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
// comment out not needed
//Square Falling
// function fallingFunction() {
// $("#" + idGenerated).css({"margin-top": "100px",});
// }
// var squareGenerationInterval = setInterval(fallingFunction, 1000);
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
#keyframes slidein {
from {
top: 0;
}
to {
top: calc(100% - 200px);
}
}
div.sq {
animation-name: slidein;
animation-duration: 2s;
animation-iteration-count: 1;
top: calc(100% - 200px);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
http://jsfiddle.net/apHLu/4/
Use this as your reference, Every time the text is clicked, the div falls down..
Keeping this as reference, use a setTimeout function for a few seconds ( may be 1-2 seconds ) on your sqaureGenerator() function and put fallingFunction() as a callback function running the Reference Code to make the objects fall
I would use transition. I wouldn't use jQuery these days, since it's now easy to do nearly anything just as easily with raw JavaScript. Including a small library for reuse, here's a full example of what your code might look like:
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, beacon, S, Q, hC, aC, rC, tC, shuffle, rand, DropBox;
addEventListener('load', ()=>{
get = (url, func, responseType = 'json', context = null)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
x.send();
return x;
}
post = function(url, send, func, responseType ='json', context = null){
const x = new XMLHttpRequest;
if(typeof send === 'object' && send && !(send instanceof Array)){
const c = context || x;
x.open('POST', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
x.send(d);
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
beacon = function(url, send){
let r = false;
if(typeof send === 'object' && send && !(send instanceof Array)){
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
r = nav.sendBeacon(url, d);
}
else{
throw new Error('send argument must be an Object');
}
return r;
}
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = function(node, className){
return node.classList.contains(className);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
shuffle = array=>{
let a = array.slice(), i = a.length, n, h;
while(i){
n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
}
return a;
}
rand = (min, max)=>{
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
DropBox = function(width, height, backgroundColor){
this.box = M('div');
let bs = this.box.style, w, h;
w = isNaN(width) ? width : width+'px';
h = isNaN(height) ? height : height+'px';
bs.width = w; bs.height = h; bs.position = 'absolute';
bs.backgroundColor = backgroundColor;
this.setPosition = (left = 0, top = 0)=>{
bs.left = isNaN(left) ? left : left+'px';
bs.top = isNaN(top) ? top : top+'px';
return this;
}
this.setPosition();
this.moveTo = (left = null, top = null, transition = 'left 1s ease-in-out, top 1s ease-in-out')=>{
let l = isNaN(left) || left === null ? left : left+'px';
let t = isNaN(top) || top === null ? top : top+'px';
bs.transition = transition;;
if(l === null && t === null){
bs.top = 'calc(100% - '+h+')';
}
else{
bs.left = l; bs.top = t;
}
return this;
}
}
// magic happens under here
const stage = I('stage'), yellow = new DropBox(50, 50, '#cc0');
const red = new DropBox('20px', '30', '#c00'), blue = new DropBox(25, 25, '#00c');
yellow.setPosition(50, 100); red.setPosition('calc(50% - 10px)');
stage.appendChild(yellow.box); stage.appendChild(red.box);
stage.appendChild(blue.box);
setTimeout(()=>{
red.moveTo(50, 100);
setTimeout(()=>{
yellow.moveTo();
setTimeout(()=>{
blue.moveTo();
}, 250);
}, 1000);
}, 500);
}); // end load
/* css/external.css */
*{
box-sizing:border-box; font:22px Tahoma, Geneva, sans-serif; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,#stage{
width:100%; height:100%;
}
#stage{
position:relative; background:#add8e6; overflow-y:auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div id='stage'></div>
</body>
</html>
You can start reading the JavaScript at // magic happens under here. Of course, the code uses the DropBox constructor that I've made for your reuse. By the way, if you require more versatility I would do animations with canvas.
I have a function that gets me the coordinates of the position of an image when you click on it. What I want to achieve is that when I click on the image draw a point in that same position as shown in the image:
this is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg" height="500" width="500" alt="dragon">
<script>
$(document).ready(function() {
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert("X Coordinate: " + x + " Y Coordinate: " + y);
});
});
</script>
Just append an absolutely positioned element to the coordinates:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg" height="500" width="500" alt="dragon">
<script>
$(document).ready(function() {
const size = 4;
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
$(this).parent().append(`<div style="width: ${size}px; height: ${size}px; background: black; position: absolute; top: ${y + size}px; left: ${x + size}px; border-radius: ${size}px"/>`);
});
});
</script>
I would use raw JavaScript. I don't have time to fully explain right now, but may later. Good Luck!
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
// magic under here
const stage = I('stage'), human = I('human'), dot = M('div'), dotStyle = dot.style;
dot.id = 'dot';
let move = false;
function moveDot(e){
if(move === true){
let left = e.clientX, top = e.clientY;
if(!stage.contains(dot))stage.appendChild(dot);
dotStyle.left = left+'px'; dotStyle.top = top+'px';
}
}
if(mobile){
human.ontouchstart = (e)=>{
move = true; moveDot(e);
}
human.ontouchmove = moveDot;
human.ontouchend = ()=>{
move = false;
}
}
else{
human.onmousedown = e=>{
move = true; e.preventDefault(); moveDot(e);
}
human.onmousemove = moveDot;
human.onmouseup = ()=>{
move = false;
}
}
}); // end load
/* css/external.css */
*{
box-sizing:border-box;
}
html,body{
width:100%; height:100%; padding:0; margin:0; background:#ccc;
}
.main,#stage{
width:100%; height:100%;
}
#stage{
position:relative; height:100%;
}
#stage>*{
position:absolute;
}
#human{
height:100%; margin:auto; top:0; right:0; bottom;0; left:0;
}
#dot{
border:1px solid #009; border-radius:50%;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='stage'>
<img id='human' src='https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg' alt='dragon' />
</div>
</div>
</body>
</html>
How to make div id="odometerDiv" change its width on window resize so that:
above 600px width there is larger width breakpoint and
below 600px there is smaller width breakpoint?
I've tried CSS and after applying css div id="odometerDiv" stops. it has to be done inside javascript code. I'm javascirpt beginner please help :)
https://jsfiddle.net/yq9ppp2o/
Below is my attepmt:
function Odometer (parentDiv,opts) {
if (!parentDiv) throw "ERROR: Odometer object must be past a document element.";
this.digits = 6;
this.tenths = 0;
this.digitHeight = 40;
this.digitPadding = 0;
this.digitWidth = 30;
this.bustedness = 2;
this.fontStyle = "font-family: Courier New, Courier, monospace; font-weight: 900;";
this.value = -1;
for (var key in opts) { this[key] = opts[key]; }
var style = {
digits: "position:absolute; height:"+this.digitHeight+"px; width:"+(this.digitWidth-(2*this.digitPadding))+"px; "+
"padding:"+this.digitPadding+"px; font-size:"+(this.digitHeight-(2*this.digitPadding))+"px; "+
"background:black; color:white; text-align:center; "+this.fontStyle,
columns: "position:relative; float:left; overflow:hidden;"+
"height:"+this.digitHeight+"px; width:"+this.digitWidth+"px;",
highlight: "position:absolute; background:white; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
lowlight: "position:absolute; background:black; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
sidehighlight: "position:absolute; background:white; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;",
sidelowlight: "position:absolute; background:black; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;"
};
var highlights = [
"top:20%; height:32%;" + style.highlight,
"top:27.5%; height:16%;" + style.highlight,
"top:32.5%; height:6%;" + style.highlight,
"right:0%; width:6%;" + style.sidelowlight,
"left:0%; width:4%;" + style.sidehighlight,
"top:0%; height:14%;" + style.lowlight,
"bottom:0%; height:25%;" + style.lowlight,
"bottom:0%; height:8%;" + style.lowlight
];
this.setDigitValue = function (digit, val, frac) {
var di = digitInfo[digit];
var px = Math.floor(this.digitHeight * frac);
px = px + di.offset;
if (val != di.last_val) {
var tmp = di.digitA;
di.digitA = di.digitB;
di.digitB = tmp;
di.digitA.innerHTML = val;
di.digitB.innerHTML = (1+Number(val)) % 10;
di.last_val = val;
}
if (px != di.last_px) {
di.digitA.style.top = (0-px)+"px";
di.digitB.style.top = (0-px+this.digitHeight)+"px";
di.last_px = px;
}
};
this.set = function (inVal) {
if (inVal < 0) throw "ERROR: Odometer value cannot be negative.";
this.value = inVal;
if (this.tenths) inVal = inVal * 10;
var numb = Math.floor(inVal);
var frac = inVal - numb;
numb = String(numb);
for (var i=0; i < this.digits; i++) {
var num = numb.substring(numb.length-i-1, numb.length-i) || 0;
this.setDigitValue(this.digits-i-1, num, frac);
if (num != 9) frac = 0;
}
};
this.get = function () {
return(this.value);
};
var odometerDiv = document.createElement("div")
odometerDiv.setAttribute("id","odometer");
odometerDiv.style.cssText="text-align: left";
parentDiv.appendChild(odometerDiv);
var digitInfo = new Array();
for (var i=0; i < this.digits; i++) {
var digitDivA = document.createElement("div");
digitDivA.setAttribute("id","odometer_digit_"+i+"a");
digitDivA.style.cssText=style.digits;
var digitDivB = document.createElement("div");
digitDivB.setAttribute("id","odometer_digit_"+i+"b");
digitDivB.style.cssText = style.digits;
var digitColDiv = document.createElement("div");
digitColDiv.style.cssText = style.columns;
digitColDiv.appendChild(digitDivB);
digitColDiv.appendChild(digitDivA);
for (var j in highlights) {
var hdiv = document.createElement("div");
hdiv.innerHTML="<p></p>"; // For Dumb IE
hdiv.style.cssText = highlights[j];
digitColDiv.appendChild(hdiv);
}
odometerDiv.appendChild(digitColDiv);
var offset = Math.floor(Math.random()*this.bustedness);
digitInfo.push({digitA:digitDivA, digitB:digitDivB, last_val:-1, last_px: -1, offset:offset});
};
if (this.tenths) {
digitInfo[this.digits - 1].digitA.style.background = "red";
digitInfo[this.digits - 1].digitB.style.background = "red";
digitInfo[this.digits - 1].digitA.style.color = "#000000";
digitInfo[this.digits - 1].digitB.style.color = "#000000";
}
if (this.value >= 0) this.set(this.value);
}
//This is the function which is to start the odometer but it does not work, I am javascript beginner please help :)
//<![CDATA[
var n = 0;
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
myOdometer.set(0);
update();
}
function update () {
n=n+0.01
myOdometer.set(n);
setTimeout(update, 200);
}
//]]>
startcounting();
$('button').click(function() {
var currentvalue = myOdometer.get();
$('#value').text(currentvalue);
});
#odometerDiv {
height:60px;
}
#value {
width:400px;
height:40px;
margin:20px 0;
text-align:center;
line-height:40px;
font-size:20px;
background:orangered;
}
button {
width:100px;
height:20px;
}
<div id="odometerDiv" style="width:100%;"></div>
Just use media queries in your css:
#odometerDiv {
// Styles for when the screen is wider than or equal to 600px
}
#media (max-width: 600px) {
#odometerDiv {
// Styles for when the screen is less than 600px
}
}
After following two YouTube lessons, I now have a nice arrow widget that fades in, rotates to 180 degrees and fades out controlled from one button. I do not know how to make the arrow rotate back to 0 on the second click of this button.
Probably not the most elegant of code, but here we are:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fade In and Out</title>
<style type="text/css">
div.contentbox {
width: 50px;
height: 50px;
padding: 20px;
opacity: 0;
}
</style>
<script type="text/javascript">
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element) {
var target = document.getElementById(element)
target.style.display = "block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
fade_in_from++;
if(fade_in_from == 10) {
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')', 50);
}
function fadeOut(element) {
var target = document.getElementById(element)
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0) {
target.style.opacity = 0;
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')', 50);
}
var looper;
var degrees = 0;
function rotateAnimation(el,speed)
{
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout ('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 179){
clearTimeout(looper)
}
}
</script>
</head>
<body>
<button onmouseover="fadeIn('arrow_box')": onmouseout="fadeOut('arrow_box')": onclick="rotateAnimation('arrow',5)">fade in/out</button>
<div id="arrow_box" class="contentbox"><img id="arrow" img src="images/Arrow.png" width="50" height="50" alt="Arrow" /></div>
</body>
</html>
Please help.
Create a new variable to remember the direction and then increment or decrement the degrees depending on which direction you want to go.
Here is a JSfiddle link of a working solution.
var looper;
var degrees = 0;
var direction = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
}else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout
('rotateAnimation(\''+el+'\','+speed+')',speed);
if(direction === 0){
degrees++;
if(degrees > 179){
direction = 1;
clearTimeout(looper);
}
}else {
degrees--;
if(degrees < 1){
direction = 0;
clearTimeout(looper);
}
}
}
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>