So I am working on creating a custom alert box. I've got most of the code the way I want it.
What I Want:
What I would like is to click the minus to fade the alert box so you can view the html behind it.
What is Wrong:
My issue is the min.onclick code does not click (clicking the minus sign does nothing).
See Below:
var b = document.getElementById('button-container');
var bg = document.createElement('div');
bg.setAttribute('id', 'alert-box');
bg.setAttribute('class','alert');
b.appendChild(bg);
var box = document.createElement('div');
box.setAttribute('id', 'alert-text');
box.setAttribute('class','alert-content');
box.setAttribute('display', 'block');
box.innerHTML = 'Fancy stuff happens here!<br>Look chess pieces';
bg.appendChild(box);
var min = document.createElement('span');
min.setAttribute('id','alert-min');
min.setAttribute('class','alert-min');
min.innerHTML = '−';
var s = true;
min.onclick = function() {
console.log('pressed!');
if(s) {
box.style.opacity = '.25';
s = false;
}
else{
box.style.opacity = '1';
s = true;
}
};
box.appendChild(min);
box.innerHTML += '<br><br>';
var images = ['q', 'n', 'r', 'b'];
var t = ['1/15', '7/70', '7/72', 'b/b1'];
for(var i = 0; i < images.length; i++) (function(i){
var btn = document.createElement('button');
btn.setAttribute('class','alert-button');
btn.setAttribute('id',images[i]+'btn');
btn.onclick = function () {
console.log('You clicked: ', images[i]);
};
box.appendChild(btn);
var img = document.createElement('img');
img.setAttribute('id',images[i]+'img');
img.setAttribute('src','https://upload.wikimedia.org/wikipedia/commons/thumb/'+t[i]+'/Chess_'+images[i]+'lt45.svg/45px-Chess_'+images[i]+'lt45.svg.png');
img.setAttribute('class','alert-image');
btn.appendChild(img);
})(i);
.alert {
display: block;
position: fixed;
z-index: 1;
padding-top: 10px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.alert-content {
background-color: #daac27;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.alert-min {
color: #fff;
float: right;
font-size: 28px;
font-weight: bold;
}
.alert-min:hover,
.alert-min:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<br><br><br>
O no! You can't see me!
<div id="button-container">
</div>
To be honest I have no idea why your script does not work. I did nothing but appending the close "button" after that loop. Now the click handler is working.
edit:
i also edited the other console.log due to it printed undefined
var b = document.getElementById('button-container');
var bg = document.createElement('div');
bg.setAttribute('id', 'alert-box');
bg.setAttribute('class','alert');
b.appendChild(bg);
var box = document.createElement('div');
box.setAttribute('id', 'alert-text');
box.setAttribute('class','alert-content');
box.setAttribute('display', 'block');
box.innerHTML = 'Fancy stuff happens here!<br>Look chess pieces';
bg.appendChild(box);
box.innerHTML += '<br><br>';
var images = ['q', 'n', 'r', 'b'];
var t = ['1/15', '7/70', '7/72', 'b/b1'];
for(var i = 0; i < images.length; i++) {
var btn = document.createElement('button');
btn.setAttribute('class','alert-button');
btn.setAttribute('id',images[i]+'btn');
let tmp = images[i]
btn.onclick = function () {
console.log('You clicked: ', tmp);
};
box.appendChild(btn);
var img = document.createElement('img');
img.setAttribute('id',images[i]+'img');
img.setAttribute('src','https://upload.wikimedia.org/wikipedia/commons/thumb/'+t[i]+'/Chess_'+images[i]+'lt45.svg/45px-Chess_'+images[i]+'lt45.svg.png');
img.setAttribute('class','alert-image');
btn.appendChild(img);
}
var min = document.createElement('span');
min.setAttribute('id','alert-min');
min.setAttribute('class','alert-min');
min.innerHTML = '−';
var s = true;
min.onclick = function() {
console.log('pressed!');
if(s) {
box.style.opacity = '.25';
s = false;
}
else{
box.style.opacity = '1';
s = true;
}
};
box.appendChild(min);
.alert {
display: block;
position: fixed;
z-index: 1;
padding-top: 10px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.alert-content {
background-color: #daac27;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.alert-min {
color: #fff;
float: right;
font-size: 28px;
font-weight: bold;
}
.alert-min:hover,
.alert-min:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<br><br><br>
O no! You can't see me!
<div id="button-container">
</div>
Related
I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)
I was searching for autocomplete examples in pure javascript, and I found a pretty good example on JSFiddle, but it has a Bug that I'm trying to figure it out how to fix.
The autocomplete only autocompletes the text if you click at the paragraph twice
Code:
var db = [
"drawLine",
"drawCircle",
"drawCircleMore",
"fillLine",
"fillCircle",
"fillCircleMore"
];
function popupClearAndHide() {
autocomplete_result.innerHTML = "";
autocomplete_result.style.display = "none";
}
function updPopup() {
if (!autocomplete.value) {
popupClearAndHide();
return;
}
var a = new RegExp("^" + autocomplete.value, "i");
for (var x = 0, b = document.createDocumentFragment(), c = false; x < db.length; x++) {
if (a.test(db[x])) {
c = true;
var d = document.createElement("p");
d.innerText = db[x];
d.setAttribute("onclick", "autocomplete.value=this.innerText;autocomplete_result.innerHTML='';autocomplete_result.style.display='none';");
b.appendChild(d);
}
}
if (c == true) {
autocomplete_result.innerHTML = "";
autocomplete_result.style.display = "block";
autocomplete_result.appendChild(b);
return;
}
popupClearAndHide();
}
autocomplete.addEventListener("keyup", updPopup);
autocomplete.addEventListener("change", updPopup);
autocomplete.addEventListener("focus", updPopup);
#autocomplete {
border: 1px solid silver;
outline: none;
margin: 0;
background: #fff;
}
#autocomplete_result {
border: 1px solid silver;
border-top: 0;
position: absolute;
overflow: auto;
max-height: 93px;
background: #fff;
}
#autocomplete,
#autocomplete_result {
width: 200px;
box-sizing: border-box;
}
#autocomplete,
#autocomplete_result p {
padding: 4px;
margin: 0;
color: #000;
}
#autocomplete_result p:nth-child(2n+1) {
background: #f6f6f6;
}
#autocomplete_result p:hover {
background: #e5e5e5;
}
<input id="autocomplete" type="text" />
<div id="autocomplete_result" style="display: none;"></div>
On change event is trigger before the click event can complete
Removing the on change call would fix the issue. Great suggestion from the comment below by 'imvain2' to replace "keyup" event listener with "input" event listener. This would trigger on any input, not only "keyup".
Demo: https://jsfiddle.net/hexzero/qrwgh7pj/
autocomplete.addEventListener("input", updPopup);
autocomplete.addEventListener("focus", updPopup);
I want to make Thumbnail Image-Video Slider dynamic using javascript only, here i created a container in which i added some images through javascript, but now i want to slide this images with Next and Previous Buttons and also on swipe mouse slider should slide.
This is the Latest Code whatever i did now i am getting problem in NEXT & PREVIOUS Buttons. i want onclick of NEXT & PREVIOUS image slider should slide Backward and Forward
This is the Output what i am getting from this code
and images should come in only one Row
Please Help me !!
$(document).ready(function ()
{
function PhotoGallery()
{
this.index = 0;
this.holder = [];
var container = document.getElementById('thumbs_container');
var nextButton = document.createElement('button');
nextButton.className = 'next';
nextButton.innerHTML = '❯';
container.appendChild(nextButton);
var prevButton = document.createElement('button');
prevButton.className = 'previous';
prevButton.innerHTML = '❮';
container.appendChild(prevButton);
container = $(window).width();
nextButton.addEventListener('click', this.next);
prevButton.addEventListener('click', this.previous);
this.create = function (name, src) {
var container = document.getElementById('thumbs_container');
var img = document.createElement('img');
img.src = src;
img.alt = name;
img.className = 'thumb';
img.style.width = '300px';
img.style.height = '150px;';
container.appendChild(img);
this.holder.push({
index: ++this.index,
ele: img
})
}
this.next = function () {
this.holder[this.index].ele.style.display = 'none';
this.holder[++this.index].ele.style.display = block;
}
this.previous = function () {
this.holder[this.index].ele.style.display = 'none';
this.holder[--this.index].ele.style.display = 'block';
}
}
var photoGallery = new PhotoGallery();
photoGallery.create('1', 'img/1.jpg');
photoGallery.create('2', 'img/2.jpg');
photoGallery.create('3', 'img/3.jpg');
photoGallery.create('4', 'img/4.jpg');
photoGallery.create('5', 'img/5.jpg');
photoGallery.create('6', 'img/6.jpg');
photoGallery.create('7', 'img/7.jpg');
photoGallery.create('8', 'img/8.jpg');
photoGallery.create('9', 'img/9.jpg');
photoGallery.create('10','img/10.jpg');
#thumbs_container {
margin: 400px auto; /*center-aligned*/
width: 100%; /*width:400px;*/
padding: 4px 40px; /*Gives room for arrow buttons*/
box-sizing: border-box;
position: relative;
background-color: red;
-webkit-user-select: none;
user-select: none;
/*max-width: 1600px;
max-height: 600px;*/
overflow:hidden;
}
.thumb{
margin-right: 1px;
}
.previous {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: absolute;
margin-left: -33px;
margin-top: 63px;
}
.next {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: absolute;
margin-left: 1822px;
margin-top: 63px;
}
<div id='thumbs_container'></div>
This is not a comprehensive answer but it should point you in the right direction.
(function() {
function PhotoGallery() {
this.index = 0;
this.holder = [];
this.setIndexVisible = true;
// When next funtion is called swap the display properties accordingly
this.next = function() {
console.log(this.index);
this.holder[this.index].ele.style.display = 'none';
this.holder[this.index+1].ele.style.display = 'block';
this.index+=1;
}
// Ditto as above according the requirement
this.previous = function() {
this.holder[this.index].ele.style.display = 'none';
this.holder[this.index-1].ele.style.display = 'block';
this.index-=1;
}
//create a button each for previous and next
var container = document.getElementById('thumbs_container');
let nextButton = document.createElement('button');
nextButton.className="next";
nextButton.id = "next";
container.appendChild(nextButton);
//style the button
// Listen to the click event and call the corresponsing function
nextButton.addEventListener('click', this.next.bind(this));
this.create = function(name, src) {
var container = document.getElementById('thumbs_container');
var img = document.createElement('img');
img.src = src;
img.alt = name;
img.className = 'thumb';
img.style.width = '200px';
if(this.setIndexVisible && this.index===0)
img.style.display = 'block';
else
img.style.display = 'none';
container.appendChild(img);
this.holder.push({
index: this.holder.length,
ele: img
})
}
}
var photoGallery = new PhotoGallery();
photoGallery.create('RED SQUARE', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Red.svg/2000px-Red.svg.png');
photoGallery.create('BLUE SQUARE', 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/000080_Navy_Blue_Square.svg/600px-000080_Navy_Blue_Square.svg.png')
})();
UPDATE : Please try and understand the code and modify it to fulfill your requirements. You might have to update the next and previous functions and also some of the logic to make it a]usable. This is just a blueprint of how to do it.
Here is a jsbin link : https://jsbin.com/ginuvonusi/edit?html,css,js,console,output
var leftFrom = 10;
var scrollPosition = 0;
var scrollOffSet = 400;
$(document).ready(function () {
function PhotoGallery() {
$('#thumbs_container').css('width', '100%');
$('#thumbs_container').css('position', 'absolute');
$('#thumbs_container').css('overflow-y', 'hidden');
//$('#thumbs_container').css('left', '1.9%')
$('#thumbs_container').css('float', 'left');
$('#thumbs_container').css('height', '215px')
var container = document.getElementById('thumbs_container');
var nextButton = document.createElement('button');
nextButton.className = 'next';
nextButton.innerHTML = '❯';
container.appendChild(nextButton);
var next = function () {
console.log("Next Clicked" + " " + $('#thumbs_container').width());
if ((scrollPosition + scrollOffSet) < $('#thumbs_container').width()) {
scrollPosition = scrollPosition + scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
}
else {
if ((scrollPosition + scrollOffSet) > $('#thumbs_container').width())
scrollPosition = scrollPosition + scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
}
}
var prevButton = document.createElement('button');
prevButton.className = 'previous';
prevButton.innerHTML = '❮';
container.appendChild(prevButton);
var previous = function ()
{
console.log('Clicked Left');
var leftOffSet = $('#thumbs_container').scrollLeft();
console.log("leftOffset" + " " + leftOffSet);
if ((leftOffSet - scrollOffSet) > 0) {
scrollPosition = scrollPosition - scrollOffSet;
$('#thumbs_container').animate({ scrollLeft: scrollPosition }, 750);
} else {
if (leftOffSet > 0)
$('#thumbs_container').animate({ scrollLeft: 0 }, 750);
}
}
this.imagecreate = function (name, src) {
var container = document.getElementById('thumbs_container');
var img = document.createElement('img');
img.src = src;
img.alt = name;
img.className = 'thumb';
img.style.width = '300px';
img.style.height = '150px';
img.style.position = 'absolute';
img.style.left = leftFrom + 'px';
leftFrom = leftFrom + 310;
container.appendChild(img);
}
this.videocreate = function (src, type) {
var container = document.getElementById('thumbs_container');
var video = document.createElement('video');
var source = document.createElement('source');
source.src = src;
source.type = type;
video.autoplay = true;
video.loop = true;
video.controls = false;
video.style.display = 'inline-block';
video.style.width = '260px';
video.style.height = '260px';
video.style.position = 'absolute';
video.style.top = '-41px';
video.style.left = leftFrom + 'px';
leftFrom = leftFrom + 270;
video.appendChild(source);
container.appendChild(video);
}
nextButton.addEventListener('click', next);
prevButton.addEventListener('click', previous);
}
var photoGallery = new PhotoGallery();
photoGallery.imagecreate('1', 'img/1.jpg');
photoGallery.imagecreate('2', 'img/2.jpg');
photoGallery.imagecreate('3', 'img/3.jpg');
photoGallery.imagecreate('4', 'img/4.jpg');
photoGallery.videocreate('img/mcvideo.mp4', 'video/mp4');
photoGallery.imagecreate('5', 'img/5.jpg');
photoGallery.imagecreate('6', 'img/6.jpg');
photoGallery.imagecreate('7', 'img/7.jpg');
photoGallery.imagecreate('8', 'img/8.jpg');
photoGallery.videocreate('img/SampleVideo_640x360_1mb.mp4', 'video/mp4');
photoGallery.imagecreate('9', 'img/9.jpg');
photoGallery.imagecreate('10', 'img/10.jpg');
photoGallery.imagecreate('11', 'img/006.jpg');
photoGallery.videocreate('img/small.mp4', 'video/mp4');
photoGallery.imagecreate('12', 'img/007.jpg');
});
#thumbs_container {
width: 100%; /*width:400px;*/
padding: 14px 40px; /*Gives room for arrow buttons*/
box-sizing: border-box;
position: relative;
background-color: red;
-webkit-user-select: none;
user-select: none;
/*max-width: 1600px;
max-height: 600px;*/
overflow:hidden;
}
.thumb{
margin-right: 1px;
}
button{position: fixed;
top: 40%;
z-index: 99999;
left: 50%;
background-color: #4CAF50;
color: #fff;
border: none;
height: 30px;
width: 30px;
line-height: 30px;}
.previous {
background-color: #4CAF50;
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: fixed;
margin-left: -33px;
top: 7%;
left: 2%;
}
.next {
background-color: #4CAF50;
border: none;
color: white;
padding: 2px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
position: fixed;
left: 98%;
top: 7%;
}
.round {
border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DynamicSlider</title>
<!--<link href="css/thumbs2.css" rel="stylesheet" />
<link href="css/thumbnail-slider.css" rel="stylesheet" />
<script src="js/thumbnail-slider.js" type="text/javascript"></script>
<script src="js/readImages.js"></script>-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>-->
<script src="js/jquery1.6.2.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<link href="css/DynamicSlider.css" rel="stylesheet" />
<script src="js/DynamicSlider.js"></script>
</head>
<body>
<div id='thumbs_container'>
</div>
</body>
</html>
I have to do some kind of ToDo list, where I have input and button to Add item to ul list. And now I done everything except compare every li item with input value. My question is how to compare every li content with value input to prevent duplicate items. Here is the code https://jsfiddle.net/qoLtxfaw/1/
// Variables
var ul = document.getElementById("taskList");
var task = document.getElementById("task");
var btn = document.querySelector('button');
var listItem = document.getElementsByTagName("LI");
// Append close btn to each list item
for (var i = 0; i < listItem.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
listItem[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("js-close");
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
// proveravati ima li ul odnosno liste, ukoliko ne proverimo a nema ceo kod ce prestati da se izvrsava
if (ul) {
ul.onmouseover = function(event) {
var target = event.target;
target.style.background = '#efebeb';
};
ul.onmouseout = function(event) {
var target = event.target;
target.style.background = '';
};
}
// Add item to list on btn
btn.addEventListener('click', addItem);
// Add item to list on enter
task.onkeyup = function(e) {
if (e.keyCode == 13) {
addItem();
}
};
// // Add item to list
function addItem() {
var li = document.createElement("li");
var inputValue = document.getElementById('task').value;
li.setAttribute('id', task.value);
li.appendChild(document.createTextNode(task.value));
// ul.appendChild(li);
// compare every li item with inputValue
if (inputValue) { //if input value is true and has some value
//go trough all li items
for (var i = 0; i < listItem.length; i++) {
// compare every li item with inputValue
}
// Duplicate values don't allow in list
if (!inputValue) {
alert("No empty values are allowed!");
li.className = 'js-btn-disable';
} else {
ul.appendChild(li);
}
document.getElementById("task").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
li.appendChild(span);
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
}
}
#wrapper {
width: 500px;
margin: 0 auto;
background: #00bcd4;
border: 1px solid #f1f0f0;
padding-left: 10px;
font-size: 1.2em;
}
#wrapper #task {
background: transparent;
color: #ffffff;
font-size: 1.2em;
width: 80%;
height: 35px;
border: none;
border-bottom: 2px solid #ffffff;
outline: none;
margin: 15px 0 5px 0;
}
#wrapper #task ::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #ffffff;
}
#wrapper #task ::-moz-placeholder {
/* Firefox 19+ */
color: #ffffff;
}
#wrapper #task :-ms-input-placeholder {
/* IE 10+ */
color: #ffffff;
}
#wrapper #task :-moz-placeholder {
/* Firefox 18- */
color: #ffffff;
}
#wrapper button {
font-size: 1.2em;
border: 2px solid #ffffff;
background: transparent;
color: #ffffff;
padding: 5px 10px;
outline: none;
cursor: pointer;
}
#wrapper ul#taskList {
padding: 0;
background: #ffffff;
list-style-type: none;
text-align: left;
margin-bottom: 0;
margin-left: -10px;
}
#wrapper ul#taskList li {
padding: 10px;
position: relative;
cursor: pointer;
}
/* Style the close button */
.js-close {
position: absolute;
right: 0;
top: 0;
padding: 10px;
}
.js-close:hover {
color: #ffffff;
}
.js-hide {
display: none;
}
.js-background {
background: #efebeb;
}
.js-btn-disable {
opacity: 0.65;
cursor: not-allowed;
}
/*# sourceMappingURL=style.css.map */
<div id="wrapper">
<input type="text" id="task" />
<button>Add</button>
<ul id="taskList"></ul>
</div>
Have a look at this. I use firstChild and I moved the validation to the top of the function.
I use the inputValue after validating it but task everywhere else.
DRY - Don't Repeat Yourself
// Variables
var ul = document.getElementById("taskList");
var task = document.getElementById("task");
var btn = document.querySelector('button');
var listItem = document.getElementsByTagName("LI");
task.focus();
// Append close btn to each list item
for (var i = 0; i < listItem.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
listItem[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("js-close");
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
// proveravati ima li ul odnosno liste, ukoliko ne proverimo a nema ceo kod ce prestati da se izvrsava
if (ul) {
ul.onmouseover = function(event) {
var target = event.target;
target.style.background = '#efebeb';
};
ul.onmouseout = function(event) {
var target = event.target;
target.style.background = '';
};
}
// Add item to list on btn
btn.addEventListener('click', addItem);
// Add item to list on enter
task.onkeyup = function(e) {
if (e.keyCode == 13) {
addItem();
}
};
// // Add item to list
function addItem() {
var inputValue = task.value.trim();
task.value = "";
task.focus();
// Empty or Duplicate values don't allow in list
if (!inputValue) {
alert("No empty values are allowed!");
return
}
var listItem = document.querySelectorAll("#taskList li");
for (var i = 0; i < listItem.length; i++) {
if (inputValue == listItem[i].firstChild.textContent) {
alert("No duplicate values are allowed!");
return
}
}
var li = document.createElement("li");
li.setAttribute('id', inputValue);
li.appendChild(document.createTextNode(inputValue));
ul.appendChild(li);
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "js-close";
span.appendChild(txt);
li.appendChild(span);
for (var i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.className = 'js-hide';
}
}
}
#wrapper {
width: 500px;
margin: 0 auto;
background: #00bcd4;
border: 1px solid #f1f0f0;
padding-left: 10px;
font-size: 1.2em;
}
#wrapper #task {
background: transparent;
color: #ffffff;
font-size: 1.2em;
width: 80%;
height: 35px;
border: none;
border-bottom: 2px solid #ffffff;
outline: none;
margin: 15px 0 5px 0;
}
#wrapper #task ::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #ffffff;
}
#wrapper #task ::-moz-placeholder {
/* Firefox 19+ */
color: #ffffff;
}
#wrapper #task :-ms-input-placeholder {
/* IE 10+ */
color: #ffffff;
}
#wrapper #task :-moz-placeholder {
/* Firefox 18- */
color: #ffffff;
}
#wrapper button {
font-size: 1.2em;
border: 2px solid #ffffff;
background: transparent;
color: #ffffff;
padding: 5px 10px;
outline: none;
cursor: pointer;
}
#wrapper ul#taskList {
padding: 0;
background: #ffffff;
list-style-type: none;
text-align: left;
margin-bottom: 0;
margin-left: -10px;
}
#wrapper ul#taskList li {
padding: 10px;
position: relative;
cursor: pointer;
}
/* Style the close button */
.js-close {
position: absolute;
right: 0;
top: 0;
padding: 10px;
}
.js-close:hover {
color: #ffffff;
}
.js-hide {
display: none;
}
.js-background {
background: #efebeb;
}
.js-btn-disable {
opacity: 0.65;
cursor: not-allowed;
}
/*# sourceMappingURL=style.css.map */
<div id="wrapper">
<input type="text" id="task" />
<button>Add</button>
<ul id="taskList"></ul>
</div>
I've got some kind of drop down menu dynamically appending to differents divs. Problem is, when someone click on "close", then style.display = "none" wont work. I can change background, opacity, size but i cant hide it.
Code looks like this:
<style>
html, body{
height: 98%;
}
#editorViewport{
width: 90%;
height: 100%;
min-width: 400px;
min-height: 300px;
position: relative;
margin: 0 auto;
border: 1px solid red;
}
#movingElementsContainer{
display: none;
top: 0px;
left: 0px;
}
#addStartingElementBtn{
width: 60px;
height: 60px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
#addStartingElementBtn:hover{
background-color: #c9eac6;
border: 1px solid grey;
cursor: pointer;
}
#elementsMenuContainer{
width: 150px;
border: 1px solid grey;
background-color: white;
min-height: 100px;
padding: 5px;
position: absolute;
z-index: 2;
display: none;
}
.elementOption{
width: 90%;
padding: 5px;
border: 1px solid grey;
}
.elementOption:hover{
border: 1px solid red;
cursor: pointer;
}
</style>
<body>
<div id="editorViewport">
<div id="addStartingElementBtn" data-Owner="starting" data-Side="starting" class="openElementsMenu">
Click!
</div>
</div>
<div id="movingElementsContainer">
<div id="elementsMenuContainer" data-Open="false" data-Owner="" data-Side="">
<div data-Kind="1" class="elementOption">
One
</div>
<div data-Kind="2" class="elementOption">
Two
</div>
<div data-Kind="3" class="elementOption">
Three
</div>
<div data-Kind="99" class="elementOption">
Close
</div>
</div>
</div>
</body>
<script type="text/javascript">
function prepareEventHandlers(){
var openElementsMenu = document.getElementsByClassName("openElementsMenu");
var event = window.attachEvent ? 'onclick' : 'click';
for(var i = 0; i < openElementsMenu.length; i++){
if(openElementsMenu[i].addEventListener){
openElementsMenu[i].addEventListener('click', elementsMenu, false);
}else{
openElementsMenu[i].attachEvent('onclick', elementsMenu);
}
}
var elementOption = document.getElementsByClassName("elementOption");
for(var i = 0; i < elementOption.length; i++){
if(elementOption[i].addEventListener){
elementOption[i].addEventListener('click', selectElementToCreate, false);
}else{
elementOption[i].attachEvent('onclick', selectElementToCreate);
}
}
}
window.onload = function(){
prepareEventHandlers();
}
var totalElements = 0;
var editorViewport = "editorViewport";
var selectedElementId = "";
var elementsMenu = function(){
var elementsMenu = document.getElementById("elementsMenuContainer")
this.appendChild(elementsMenu);
elementsMenu.style.display = "block";
elementsMenu.style.left = 61 + "px";
elementsMenu.style.top = "0px";
elementsMenu.setAttribute("data-Open", "true");
elementsMenu.setAttribute("data-Owner", this.getAttribute("data-Owner"));
elementsMenu.setAttribute("data-Side", this.getAttribute("data-Side"));
}
var selectElementToCreate = function(){
var dataKind = this.getAttribute('data-Kind');
var parentNode = document.getElementById(this.parentNode.id);
alert(dataKind)
if(dataKind == "99"){
parentNode.style.display = "none"
parentNode.setAttribute("data-Open", "false");
parentNode.setAttribute("data-Owner", "");
parentNode.setAttribute("data-Side", "");
}
}
</script>
Here is a JSFiddle
Many thanks for any advise!
var selectElementToCreate = function(e){
var dataKind = this.getAttribute('data-Kind');
var parentNode = document.getElementById(this.parentNode.id);
alert(dataKind)
if(dataKind == "99"){
console.log(parentNode);
parentNode.style.display = "none"
parentNode.setAttribute("data-Open", "false");
parentNode.setAttribute("data-Owner", "");
parentNode.setAttribute("data-Side", "");
alert("Wont Close :");
}
e.stopPropagation();
}
You are moving the element into the clicked element.
var elementsMenu = document.getElementById("elementsMenuContainer")
this.appendChild(elementsMenu);
At first the menu item's click handler is executed which sets the display property to none and as the click event bubbles then the event handler of the wrapper element is executed and sets the display property to block.
You should stop the propagation of the event using stopPropagation method of the event object.
var selectElementToCreate = function (event) {
event.stopPropagation();
var dataKind = this.getAttribute('data-Kind');
var parentNode = this.parentNode;
if (dataKind == "99") {
parentNode.style.display = "none";
// ...
}
}