I am currently working to create a custom alert box for any errors and below is the code I am using, the alert box is appearing fine but it's not auto-closing after 600 milliseconds, its only closed after the manual click of the close button. what I am doing wrong here and how to auto-disappear the alert box
I moved the setTimeout outside the click event and set the div value:
function displayError(errorMessage) {
var messageObject = "<div class='alert' id='alertbox'><span class='closebtn' id='closebtn'>×</span><strong><font color='#f44336;'>Error!</font></strong>"+errorMessage+"</div>"
document.getElementById("divMessageContainer").innerHTML += messageObject;
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
var div = close[i].parentElement;
setTimeout(function(){div.style.display = "none"; }, 600);
close[i].onclick = function(){
div.style.opacity = "0";
}
}
}
div#alertbox{padding: 10px;bottom: 40px;left: 5px; max-width: 800px; margin-left: auto;margin-right: auto;z-index: 99; max-width: 700px; color: #000;background-color: #EEE;border-radius: 10px; padding-right: 5px; padding-left: 10px;}
span#closebtn {margin-left: 15px;color: black;font-weight: bold;float: right;font-size: 22px;line-height: 20px; cursor: pointer; transition: 0.3s;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="divMessageContainer"></div>
<button onclick="displayError()">button</button>
</body>
</html>
I have followed the below steps and fixed the issue reported here, The below approach allowed me to show multiple alert box at the same time and auto close them based on the message number instead of close all the alert box at the same time
<!DOCTYPE html>
<html>
<style>
div.alertbox{padding: 10px;bottom: 40px;left: 5px; max-width: 800px; margin-left: auto;margin-right: auto;z-index: 99; max-width: 700px; color: #000;background-color: #EEE;border-radius: 10px; padding-right: 5px; padding-left: 10px;}
span#closebtn {margin-left: 15px;color: black;font-weight: bold;float: right;font-size: 22px;line-height: 20px; cursor: pointer; transition: 0.3s;}
</style>
<body>
<div id="divMessageContainer"></div>
<button onclick="displayError()">button</button>
</body>
<script>
var messageCount = 0;
var messageTimeout = 3000;
function displayError(errorMessage) {
var messageObject = "<div class='alertbox' id='alertbox"+messageCount+"'><span class='closebtn' id='closebtn'>×</span><strong><font color='#f44336;'>Error!</font></strong>"+errorMessage+"</div>"
document.getElementById("divMessageContainer").innerHTML += messageObject;
var messageID = messageCount;
setTimeout(function(){removeElement("alertbox" + messageID); }, messageTimeout);
closeAlertbox();
}
function removeElement(id) {
if (document.getElementById(id)) {
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
}
function closeAlertbox() {
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function(){
var div = this.parentElement;
div.style.opacity = "0";
setTimeout(function()
{ div.style.display = "none";
}, 10);
}
}
}
</script>
</html>
I would recommend using remove() to remove the alertbox, so there won't be any closebuttons left and the for-loop can be removed.
Maybe this would be a possible solution:
function displayError(errorMessage) {
var messageObject = "<div id='moo' class='alert alert-danger alert-dismissible' role='alert' auto-close='2000'><div class='alert' id='alertbox'><span class='closebtn' id='closebtn'>×</span><strong><font color='#f44336;'>Error!</font></strong>"+errorMessage+"</div>";
var container = document.getElementById("divMessageContainer");
container.innerHTML += messageObject;
var box = document.getElementById("alertbox");
var close = document.querySelector(".closebtn");
close.onclick = function(){
box.remove();
};
setTimeout(function(){
box.style.opacity = 0;
setTimeout(function() {
box.remove();
}, 1000);
}, 2000);
}
div#alertbox{padding: 10px;bottom: 40px;left: 5px; max-width: 800px; margin-left: auto;margin-right: auto;z-index: 99; max-width: 700px; color: #000;background-color: #EEE;border-radius: 10px; padding-right: 5px; padding-left: 10px; -webkit-transition: opacity 1s linear;}
span#closebtn {margin-left: 15px;color: black;font-weight: bold;float: right;font-size: 22px;line-height: 20px; cursor: pointer; transition: 0.3s;}
<div id="divMessageContainer"></div>
<button onclick="displayError()">button</button>
I also added a transition to opacity, so if the user doesn't manually close the alertbox, it will fade (in this case after 2 seconds, but you can play with that time).
function displayError(errorMessage) {
var messageObject = "<div id='moo' class='alert alert-danger alert-dismissible' role='alert' auto-close='2000'><div class='alert' id='alertbox'><span class='closebtn' id='closebtn'>×</span><strong><font color='#f44336;'>Error!</font></strong>"+errorMessage+"</div>"
document.getElementById("divMessageContainer").innerHTML += messageObject;
var close = document.getElementsByClassName("closebtn");
var i, index;
for (i = 0; i < close.length; i++) {
setTimeout(function(){
close[index].parentElement.style.display = "none";
index++;
}, 600);
close[i].onclick = function(){
var div = this.parentElement;
div.style.display = "none";
}
}
}
Try this one. Take care about loop when using async.
Related
I wanted to make two buttons, one was to move up the pages and show up when it exceeds 300px and the other was to be shown immediately and move the person who clicks to the bottom
I will add that I am new in programming
I made one button that takes a person down the page with Javascript and when I added the second it only displayed the last button
HTML
div id="TotopButton">^<span id="test"></span></div>
<div id="ToDownButton">^<span id="test2"></span></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
CSS
#TotopButton
{
background-color: red;
color: black;
font-size: 35px;
padding:10px;
position:fixed;
bottom:15px;
right:15px;
height: 50px;
width: 150px;
border:1px solid black;
text-align: center;
display:none;
}
#TotopButton:hover
{
color:white;
cursor:pointer;
}
#ToDownButton
{
Background-color: blue;
color: black;
font-size:35px;
padding:10px;
position:fixed;
bottom:15px;
left:15px;
height:50px;
width:150px;
border: 1px solid black;
text-align: center;
display: none;
}
#ToDownButton:hover
{
color:white;
cursor:pointer;
}
Javascript
window.onload = function()
{
var TotopButton = document.getElementById("TotopButton");
var test = document.getElementById("test");
window.onscroll = function ()
{
var TotopButton = document.getElementById("TotopButton");
var yScrollAxis = window.pageYOffset;
var test = document.getElementById("test");
if (yScrollAxis > 300)
{
TotopButton.style.display = 'block'
}
else
{
TotopButton.style.display = 'none'
}
test.innerHTML = " " + window.pageYOffset
}
TotopButton.onclick = function()
{
window.scrollBy(0, -1 * window.pageYOffset);
}
};
//Secon button
window.onload = function()
{
var ToDownButton = document.getElementById("ToDownButton");
var test2 = document.getElementById("test2");
window.onscroll = function()
{
var ToDownButton = document.getElementById("ToDownButton");
var yScrollAxis = window.pageYOffset;
var test2 = document.getElementById("test2");
if (yScrollAxis > 50)
{
ToDownButton.style.display = 'block'
}
else
{
ToDownButton.style.display = 'none'
}
test2.innerHTML = " " + window.pageYOffset
}
ToDownButton.onclick = function()
{
window.scrollBy(0, 1000 * window.pageYOffset);
}
};
I use a similar button, and this is my setup for the top button you described:
HTML:
[code]
<section class="floating-button">
<div class="btn-wrapper">
<a class="primary-btn" id="floating-btn" href="#bottom-form">Apply Now</a>
</div>
</section>
[more code]
<section class="final-form" id="bottom-form">
[form here]
</section>
jQuery
$(document).scroll(function() {
var y = $(this).scrollTop();
if ((y > 490) && (y < 5698)) {
$('#floating-btn').css('visibility','visible').fadeIn();
} else {
$('#floating-btn').fadeOut();
}
});
For the above script, adjust 490 to where you want the button to fade in; you can check the right place adding console.log(y); you may also want to remove the y < 5698 if you don't want to fade out the button at the bottom of the page
SCSS
.floating-button {
z-index: 1;
position: fixed;
bottom: 34px;
width: 100%;
}
I don't know how to describe this without making it more complicated.
So look at the result of the code and click on the first link with "Show", then the second one and third one.
When the second link is clicked, first one closes but text remains "Hide" and i want it to change to "Show".
So, when clicking a link, detect if any other link has text "Hide" and change it to "Show".
And please no jQuery...
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
I tried to write a solution which didn't use any javascript at all and worked using CSS alone. I couldn't get it to work though - CSS can identify focus but it can't identify blur (ie. when focus has just been removed).
So here is a solution which uses javascript and the classList API, instead:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
Like this?
Just added following to closeOther():
visible = document.querySelectorAll(".show"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].textContent="Show";
}
Im new to this but I've been having some trouble with trying to get my timer and score values back to 0 before a new game of memory starts. The values do reset, but don't show it until that value is affected. For example, the value for the number of matches never goes back to 0, it stays on 10(the max number of pairs) until you find the first match of the next game where it will then turn to 1. Does anybody know how to get the values to show 0 again when a new board is called up instead of just resetting when that value is affected?
I have already set
var turns = 0
var matches = 0
and called in them up as 0 in the function newBoard().
My timer code is:
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
Where I have called up the resetTime() function in the function newBoard().
My full code is:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
matches = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>
Both of the variables you are settings are displayed in HTML span objects.
What seems to be happening is that when you reset the Javascript variable, the value is being changed, but the span object where it is displayed to the user is being left at its previous value until it needs to be updated again.
As far as I can tell, your objects have the ids: matchNumber and Count for the match and turn variables respectively. If this is the case, try changing your code to reset the values to zero in the HTML when the variables are reset to zero.
For example:
// Reset the Javascript Count
var turns = 0
// Reset the HTML object
document.getElementById('Count').innerHTML = 0;
// Reset the Javascript Match Count
var matches = 0
// Reset the HTML object
document.getElementById('matchNumber').innerHTML = 0;
If I failed to explain this well, please comment and I'll try to clarify further.
I am not 100% sure, but you can try replacing your function with this one:
function timedCount() {
if(c>10){
//flipBack();
resetTime();
return;
}
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
I was writing code for image flip game in jquery but I am facing some problems with the click events on image in the beginning. The problems are when I click one image and click again the same image it works fine but if I click one image, the image src attribute is added to the img tag and then if I click any other image the src attribute is not added to that one for the first click because the clickCounter has the value 1 then. I employed my own logic (clickCounter). I am new to jquery. You may suggest a better way to do this. Thanks in advance.
Here is my code.
<style>
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
</style>
<body>
<div id="main">
</div>
<button id="add">Add</button>
<script src="jquery-1.11.2.js"></script>
<script>
var clickCounter = 0;
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
if(clickCounter == 0){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
clickCounter = 1;
}else{
myImage.removeAttr('src');
clickCounter = 0;
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
</script>
</body>
JSFiddle
The problem is the shared variable clickCounter which is shared between all the elements.
In this case since you have dynamic elements, you could use event delegation and then use the current src value of the img to set the new one like
$('#add').click(function () {
addElements(44);
$('#add').prop('disabled', true);
});
$('#main').on('click', '.myimg', function () {
$(this).attr('src', function (i, src) {
return src == 'back.png' ? '' : 'back.png';
}).height(100).width(100);
})
function addElements(times) {
var $main = $('#main');
for (j = 1; j <= times; j++) {
$('<img />', {
'class': 'myimg'
}).appendTo($main)
}
}
Demo: Fiddle
Instead of counter, check for 'src' attribute as shown below,
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
var attr = $(this).attr('src');
if(typeof attr == typeof undefined){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
}else{
myImage.removeAttr('src');
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
</div>
<button id="add">Add</button>
What I'm trying to accomplish is a java readmore/readless content toggle function that disable other content when one content's onclick triggers. I'm using getElementsByClassName, setTimeout, and transition.
The problem I'm having is that display: none is not responding to setTimeout. Any suggestion outside of javascript is welcome too.
Here is the Javascript:
function toggle(cont, tog, id) {
for (var i = 0; i < cont.length; i++) {
if (tog[id].innerHTML != "Click Here to Read Less!") {
/* Toggle On */
tog[id].innerHTML = "Click Here to Read Less!";
cont[id].style.height = "250px";
/* Disable other */
setTimeout(function () { cont[i].style.display = "none" }, 500);
setTimeout(function () { tog[i].style.display = "none" }, 500);
for (var x = 0; x < cont.length; x++) {
cont[x].style.opacity = "0";
tog[x].style.opacity = "0";
setTimeout(function () { cont[x].style.display = "none" }, 500);
setTimeout(function () { tog[x].style.display = "none" }, 500);
if (cont[id] == cont[x]) {
cont[id].style.opacity = "1";
tog[id].style.opacity = "1";
}
}
} else {
/* Toggle Off */
tog[id].innerHTML = "Click Here to Read More!";
cont[id].style.height = "100px";
/* Enable other */
for (var x = 0; x < cont.length; x++) {
cont[x].style.opacity = "1";
tog[x].style.opacity = "1";
cont[x].style.display = "block";
tog[x].style.display = "block";
}
}
}
}
Here is my HTML:
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
<div class="content">
<p>
Content Here!
</p>
</div>
Click Here to Read More!
And CSS for formatting sake:
/* Centering Content */
#wrapper {
margin: 0 auto;
height: auto;
width: 70%;
text-align: center;
font-family: Sans-Serif, Calibri;
}
/* Styling Content */
.content {
padding: 25px 50px;
margin: 0 auto;
height: 100px;
width: 500px;
display: block;
text-align: left;
overflow: hidden;
-webkit-transition: all 0.5s;
transition: all 0.5s;
}