how to remove the quotes or get element from this (javascript) - javascript

As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "&#10094";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "&#10095";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>

.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);

Related

Show images in quiz javascript

I'm trying to create a quiz that tests users awareness of real and fake emails. What I want to do is have the question displayed at the top saying "Real or Fake", then have an image displayed underneath which the user needs to look at to decided if it's real or fake. There are two buttons, real and fake, and regardless of whether they choose the right answer I want to swap the original image with annotated version - showing how users could spot that it was fake or real.
But I'm not sure how to show the annotated version once the answer has been submitted. Could someone help?
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("<img src= 'netflix_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'dropbox_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'gov_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'paypal_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'gmail.jpg' />", ["Real", "Fake"], "Fake")
];
//create quiz
var quiz = new Quiz(questions);
// display
populate();
body {
background-color: #538a70;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
font-size: 60px;
text-align: center;
color: #000000;
padding: 2px 0px;
}
#score {
color: #000000;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #000000;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #a0a0a0;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #00994d;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<div class="grid">
<div id="quiz">
<h1>Can you spot the fake email?</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
When user clicks button I trigger class and I add it second name, on second I have written to get swapped, I wrote you basically full project, and please read the whole comments, to understand logic
//Calling Elements from DOM
const button = document.querySelectorAll(".check");
const images = document.querySelectorAll(".image");
const answer = document.querySelector("h1");
//Declaring variable to randomly insert any object there to insert source in DOM Image sources
let PreparedPhotos;
//Our Images Sources and With them are its fake or not
//fake: true - yes its fake
//fake: false - no its real
const image = [
[
{
src:
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1200px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg",
fake: true
},
{
src:
"http://graphics8.nytimes.com/images/2012/04/13/world/europe/mona-lisa-like-new-images/mona-lisa-like-new-images-custom4-v3.jpg",
fake: false
}
],
[
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/Creacion_de_Adan__Miguel_Angel_f5adb235-bfa8-4caa-8ffb-c5328cbad953_grande.jpg?12799626327330268216",
fake: false
},
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/First-image_Fb-size_grande.jpg?10773543754915177139",
fake: true
}
]
];
//Genrating Random Photo on HTML
function setRandomPhoto() {
//Random Number which will be length of our array of Object
//if you array includes 20 object it will generate random number
// 0 - 19
const randomNumber = Math.floor(Math.random() * image.length);
//Decalaring our already set variable as Array Object
PreparedPhoto = image[randomNumber];
//Our first DOM Image is Variables first object source
images[0].src = PreparedPhoto[0].src;
//and next image is next object source
images[1].src = PreparedPhoto[1].src;
}
//when windows successfully loads, up function runs
window.addEventListener("load", () => {
setRandomPhoto();
});
//buttons click
//forEach is High Order method, basically this is for Loop but when you want to
//trigger click use forEach - (e) is single button whic will be clicked
button.forEach((e) => {
e.addEventListener("click", () => {
//decalring variable before using it
let filtered;
//finding from our DOM image source if in our long array exists
//same string or not as Image.src
//if it exists filtered variable get declared with that found obect
for (let i = 0; i < image.length; i++) {
for (let k = 0; k < 2; k++) {
if (image[i][k].src === images[0].src) {
filtered = image[i][k];
}
}
}
//basic if else statement, if clicked button is Fake and image is true
//it outputs You are correct
//if clicked button is Real and Image is false it outputs Correct
//Else its false
//Our image checking comes from filtered variable
if (e.innerText === "Fake" && filtered.fake === true) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else if (e.innerText === "Real" && filtered.fake === false) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else {
answer.innerHTML = "You are Wrong";
images.forEach((image) => {
image.classList.toggle("hidden");
});
}
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.image-fluid {
display: flex;
}
.image-fluid .image {
width: 200px;
margin: 0 10px;
transition: 0.5s;
}
.image-fluid .image:nth-child(1).hidden {
transform: translateX(110px);
}
.image-fluid .image:nth-child(2).hidden {
transform: translateX(-110px);
}
<div class="container">
<div class="image-fluid">
<img src="" class="image hidden">
<img src="" class="image hidden">
</div>
<div class="button-fluid">
<button class="check">Fake</button>
<button class="check">Real</button>
</div>
</div>
<h1></h1>

How do I programatically change a picture inside a div?

Here there is full code as you guys can see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Collage</title>
</head>
<style>
div
{
background: url("Image/191203174105-edward-whitaker-1-large-169.jpg")
;
height: 300px;
width: 300px;
}
</style>
<body>
<div id="div"></div>
<button id="button">Next</button>
<script>
As here I took variable im where I feed 3 images.
var im=[
{'img':'Image/191203174105-edward-whitaker-1-large-169.jpg',}
,{'img':'Image/5718897981_10faa45ac3_b-640x624.jpg',},
{'img':'Image/gettyimages-836272842-612x612.jpg',},
];
var a=document.getElementById('button');
var b=document.getElementById('div')
a.addEventListener('click',next);
so here according to my knowledge it should provide the link of the each pic as loop starts but in program. I dont get the desired result. Can you please help me understand why this is happening?
function next()
{
for(var i=1;i<im.length;i++)
{
b.style.background=`url(${im[i].img})`;
}
}
</script>
</body>
</html>
var i = 0;
var im = [{
'img': 'https://picsum.photos/536/354'
},
{
'img': 'https://picsum.photos/id/237/536/354'
},
{
'img': 'https://picsum.photos/seed/picsum/536/354'
}
];
var a = document.getElementById('button');
var b = document.getElementById('div')
a.addEventListener('click', next);
function next() {
console.log(i);
b.style.background = `url(${im[i].img})`;
i++;
if (i == im.length) {
i = 0;
}
}
div {
background: url("https://picsum.photos/id/1084/536/354?grayscale");
height: 300px;
width: 300px;
}
<div id="div"></div>
<button id="button">Next</button>
If you're looking to cycle through pictures on a button click, then you can't really use a loop. In the code that you posted, on the click of the button, it rapidly looped through all of the pictures. You need to create a counter, and increment it on each button click.
The snippet below I've added in a previous button as well and you can cycle through the pictures both forward and backward.
const im = {
'img1': 'https://placehold.it/300x150/ff0000/ffffff?text=image_1',
'img2': 'https://placehold.it/300x150/00ff00/ffffff?text=image_2',
'img3': 'https://placehold.it/300x150/0000ff/ffffff?text=image_3',
};
const imgDiv = document.getElementById('imgDiv')
const btnNext = document.getElementById('btnNext');
const btnPrev = document.getElementById('btnPrev');
const totImages = Object.keys(im).length;
let imgNumber = 1;
btnNext.addEventListener('click', next);
btnPrev.addEventListener('click', prev);
function next() {
imgNumber++
let img = imgNumber <= totImages ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber === totImages) btnNext.disabled = true;
if (imgNumber > 1) btnPrev.disabled = false;
}
function prev() {
imgNumber--
let img = imgNumber >= 0 ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber < totImages) btnNext.disabled = false;
if (imgNumber === 1) btnPrev.disabled = true;
}
#imgDiv {
background: url("https://placehold.it/300x150/ff0000/ffffff?text=image_1");
height: 150px;
width: 300px;
}
#btnDiv {
width: 300px;
height: auto;
position: relative;
}
#btnPrev {
position: absolute;
left: 0;
top: 0;
}
#btnNext {
position: absolute;
right: 0;
top: 0;
}
<div id="imgDiv"></div>
<div id='btnDiv'>
<button id="btnPrev" disabled>&loarr; Prev</button>
<button id="btnNext">Next &roarr;</button>
</div>

Getting blob image back to file

I am having problem converting image to blob and back to file, I mean when I convert image to blob and display on the page, chose which I want to keep and which I want to remove and after try to convert back to file and append to form data, nothing gets appended to formData and file type and size on new files from blob images are different, how can I change that? Thank you
$(document).on('click', '#addProduct', function(e) {
e.preventDefault();
var arr = [];
for(var q=0; q<$('.image-buttons').length; q++) {
var blob = $('.image-buttons').children('img').attr('src');
var fileOfBlob = new File([blob], 'image'+q);
arr.push(fileOfBlob);
}
if(arr.length < 4 && arr.length > 0){
var formData = new FormData();
$.each(arr, function(i, file) {
formData.append('images', file);
console.log(file);
});
console.log(formData);
return false;
}
});
$(document).on('change', '#images', function() {
var reg = /\.(gif|jpg|png|GIF|JPG|PNG|jpeg|JPEG)$/i;
var imageNameArray = [];
for(var j = 0; j<$("#images")[0].files.length; j++) {
if(!$("#images")[0].files[j].name.match(reg)){
imageNameArray.push($("#images")[0].files[j].name);
}
}
if(imageNameArray.length === 0 && $("#images")[0].size<2097152){
for(var e=0; e<$("#images")[0].files.length; e++) {
$('.img-button-holder').append('<div class="image-buttons"><img src="'+window.URL.createObjectURL($("#images")[0].files[e])+'"><div class="img-tools"><i class="fa fa-angle-double-left" aria-hidden="true"></i><i class="fa fa-angle-double-right" aria-hidden="true"></i><i class="fa fa-times removeImg" aria-hidden="true"></i></div></div>');
}
$('.image-display').append('<img src="'+window.URL.createObjectURL($("#images")[0].files[0])+'">');
}
});
$(document).on('click', '.image-buttons', function() {
var this_img = $(this).children('img').attr('src');
$('.image-buttons').css('border','1px solid #e0e0e0');
$(this).css('border','2px solid red');
$('.image-display').children('img').attr('src', this_img);
});
$(document).on('click', '.img-tools > .fa', function() {
var this_el = $(this).parent().parent();
if($(this).hasClass('removeImg')){
$(this_el).remove();
}else if($(this).hasClass('fa-angle-double-left')) {
var prev = $(this_el).prev();
$(this_el).insertBefore(prev);
}else if($(this).hasClass('fa-angle-double-right')) {
var next = $(this_el).next();
$(this_el).insertAfter(next);
}
});
.addNew {
width: 100%;
height: auto;
float: left;
}
.addNew > form {
width: 40%;
float: left;
height: auto;
margin-right: 5%;
}
.addNew > .image-display {
width: 55%;
float: right;
min-height: 300px;
height: auto;
border: 1px solid #e0e0e0;
position: relative;
}
.addNew .image-buttons {
width: 30%;
height: 80px;
margin: 10px 1.5%;
border: 1px solid #e0e0e0;
float: left;
overflow: hidden;
position: relative;
}
.img-button-holder {
width: 55%;
float: right;
}
.image-buttons > img, .image-display > img {
width: 100%;
height: 100%;
min-height: 100%;
min-width: 100%;
}
.image-display > img {
width: 100%;
height: auto;
min-height: auto;
min-width: 100%;
position: absolute;
bottom: 0; left: 0;
}
.img-tools {
color: red;
font-size: 2rem;
position: absolute;
width: 100%;
height: auto;
top: 0; left: 0;
}
.img-tools > i {
float: left;
width: 30%;
margin: 5px 1.5%;
cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addNew">
<form>
<input type="file" name="images" id="images" multiple>
<button id="addProduct">Add</button>
</form>
<div class="image-display"></div>
<div class="img-button-holder"></div>
</div>
A blobURI (that you miscalled blob in your code) is just a string.
The File object you create is just that string in a text/plain file.
You don't have to convert from a File to a blobURI to a File.
Just keep the initial Files, store them in a good ol' Array, manage them from there.
Create the blobURI only to display these Files (it's really just a pointer in the memory so your document (here <img>) knows how to access the file on the user disk, and hence can't be shared).
When you need to send the files, simoly take them from the Array you did the management with.
ps: Note that depending on your back-end, you might have to append a [] at the name of your formData key.
function sendToServer() {
var formData = new FormData(),
files = fileHandler.list; // grab them directly from our manager
// it's an Array, so use Array methods
files.forEach(function(file) {
// since you are on php, to be able to append multiple items in the same field,
// you need to append '[]' at the end of your fieldName
formData.append('images[]', file);
});
// send it to your server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'your_php_script');
// xhr.send(formData);
// but from SO we will just show what's inside
if (typeof formData.getAll === 'function') {
console.log(formData.getAll('images[]'));
}
}
// A basic file manager which will expose its selected files in an Array
function FileHandler(options) {
if (!options || typeof options !== 'object')
options = {};
this.options = options;
// this is really the only important part: we use an Array to store all our files
this.list = [];
this.addButton = isValidElement(options.addButton) || $('<button>', {
text: 'Add new Files'
});
// also, we use a single file input
this.input = $('<input>', $.extend(options.input || {}, {
type: 'file',
class: 'fh-input',
multiple: true,
}));
this.items_container = isValidElement(options.items_container) || $('<div>', {
class: 'fh-item-container'
});
this.preview = this.initPreview();
this.addButton.on('click', function() {
this.input.click()
}.bind(this));
this.input.on('change', this.onchange.bind(this));
this.items_container.on('click', '.fh-item .fh-remove', this.remove.bind(this));
this.items_container.on('click', '.fh-item :not(.fh-remove)', this.handleItemClick.bind(this));
this.items_container.on('load', 'img', revokeURL);
// We don't need blobURIs for anything else than loading <img> elements,
// so we can revoke them directly at load
function revokeURL(evt) {
var url = evt.currentTarget.src;
URL.revokeObjectURL(url);
}
function isValidElement(obj) {
var $obj = $(obj);
return $obj[0] && $obj[0] instanceof Element && $obj.eq(0);
}
}
FileHandler.prototype = Object.create({
add: function addFile(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $item = this.generateItem(file);
this.items_container.append($item);
// store it in our Array
this.list.push(file);
this.preview.show(file);
return $item;
},
remove: function removeFile(event) {
var $target = $(event.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file'),
index = this.list.indexOf(file);
$item.remove();
if (index > -1) {
// remove it from our Array
this.list.splice(index, 1);
}
if (this.preview.current === file) {
if (this.list.length) {
var next = index <= (this.list.length - 1) ? index : 0;
this.preview.show(this.list[next]);
} else this.preview.hide();
}
},
generateItem: function generateItem(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $cont = $('<div>', {
class: 'fh-item'
}),
$title = $('<span>', {
text: file.name || 'unknown-file (' + file.type + ')',
class: 'fh-file_name'
}),
$btn = $('<button>', {
class: 'fh-remove',
text: 'x',
title: 'remove',
name: 'remove item'
}),
$thumb = $('<div>', {
class: 'fh-thumb'
})
// a single time blobURI
.append($('<img>', {
src: URL.createObjectURL(file)
}));
$cont.data('fh.file', file);
return $cont.append(
$title,
$btn,
$thumb
);
},
onchange: function oninputchange(evt) {
// retrieve the Files contained in our single input
var fileList = this.input[0].files;
for (var i = 0; i < fileList.length; i++) {
this.add(fileList[i]);
}
},
handleItemClick: function handleItemClick(evt) {
var $target = $(evt.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file');
this.preview.show(file);
},
initPreview: function() {
var $cont = $('<div>', {
class: 'fh-preview'
}),
img = new Image();
return {
container: $cont.append(img),
update: function updatePreview(url) {},
show: function show(file) {
if (!(file instanceof Blob)) {
console.warn('Not a Blob', file);
throw new TypeError('Argument 1 must be Blob or a File');
}
if (this.current !== file) {
this.current = file;
img.src = URL.createObjectURL(file);
}
$cont.show();
},
hide: function hide() {
img.src = '#';
$cont.hide();
}
};
}
});
var fileHandler = new FileHandler({
input: {
accept: 'image/*'
}
});
$('body').append(
fileHandler.addButton,
$('<button>', {
text: 'send to server'
})
.on('click', sendToServer),
fileHandler.items_container,
fileHandler.preview.container,
);
.fh-item {
border: 1px solid;
display: inline-block;
min-width: 130px;
min-height: 130px;
vertical-align: middle;
}
.fh-file_name {
display: inline-block;
width: 100px;
overflow: hidden;
text-overflow: ellipsis;
margin: 2px 4px;
vertical-align: top;
}
.fh-remove {
box-shadow: none;
border: none;
float: right;
cursor: pointer;
}
.fh-remove:hover {
color: #CC0000;
}
.fh-thumb {
text-align: center;
width: 100%;
height: 100px;
}
.fh-thumb>img {
max-width: 100px;
max-height: 100px;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Make appear text in Javascript

I'm trying to make appear text in Javascript.
That's my code :
HTML :
<div id="t1">Ecologie</div>
<div id="t2">Planète</div>
<div id="t3">BIO</div>
<div id="t4">Responsable</div>
<div id="t5">Changement</div>
<div id="t6">Durable</div>
<script type="text/javascript">var mytimeout = setTimeout(DisplayElem(), 2000)
</script>
CSS :
#t1
{
position: absolute;
color: green;
font-size: 50px;
top: 50%;
left: 13%;
display: none;
}
#t2
{
position: absolute;
color: green;
font-size: 60px;
top: 40%;
left: 70%;
display: none;
}
and Javascript :
function Display (elem) {
elem.style.display = block;
}
var compteur = 0;
function DisplayElem()
{
compteur += 1;
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
mytimeout = setTimeout(DisplayElem(), 2000)
if(compteur == 6)
{
window.clearTimeout(mytimeout);
}
}
I got this error : Uncaught ReferenceError: block is not defined
on my line :elem.style.display = block;
When i open my page i want all of my div invisible. But after a few second i would like to have on who appear, and the next one, and the next one...
Thank you
Here is your complete working code:
var compteur = 1;
function Display (elem) {
elem.style.display = 'block';
}
function DisplayElem()
{
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
compteur += 1;
if (compteur <= 6)
setTimeout(DisplayElem, 2000);
}
DisplayElem();
See the DEMO here
You have forgotten the delimiters around the string block:
function Display (elem) {
elem.style.display = 'block';
}
Side note: Instead of setting the timeout the last time and then removing it, just skip setting it:
if (compteur < 6) {
mytimeout = setTimeout(DisplayElem(), 2000)
}

Trying to make these divs not reset position when I add new one with jquery

I have tried changing the keyup part of the code to a button and I have also tried some code to get the draggable element to store its position in the cookie but to no avail. When I change the empty tag to ready it repeats the previous lines every time. Any help would be much appreciated.
jsFiddle for original code
jsFiddle for my attempt at a button
HTML
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<textarea></textarea>
<div id="opt"></div>
CSS
d {
position: relative;
left: 0;
top: 0;
width: 60px;
height: 60px;
background: #ccc;
float: left;
font-family: arial;
font-size: 10px;
}
JavaScript
$(document).ready(function() {
$("textarea").keyup(splitLine);
function splitLine() {
$("#opt").empty();
var lines = $("textarea").val().split(/\n/g);
for (var i = 0; i < lines.length; i++) {
var ele = $("<d>");
ele.html(lines[i]);
$("#opt").append($(ele).draggable());
}
}
});
I think you shouldn't remove all your <d> and start over every time. I have made some changes in the code to reuse the old <d> so that it's position is preserved
$(document).ready(function () {
$("textarea").keyup(splitLine);
function splitLine() {
//$("#opt").empty();
var lines = $("textarea").val().split(/\n/g);
for (var i = 0; i < lines.length; i++) {
var ele;
if ($("d:eq(" + i + ")").get(0)) {
ele = $("d:eq(" + i + ")");
ele.html(lines[i]);
} else {
ele = $("<d>");
ele.html(lines[i]);
$("#opt").append($(ele).draggable());
}
}
}
});

Categories