var divNumber = 1;
$('.AddDiv').on('click', function() {
$('.Wrap').prepend($('<div class="container"><div class="count" id="div'+divNumber+'" onclick="makeCount(this.id);">My Counter</div><div class="background"></div><div class="hover"></div></div>'));
divNumber++;
});
var divNumber = 1;
$('.AddDiv').on('click', function() {
$('.Wrap').prepend($(' <div class="List"><div class="count" id="div0" onclick="makeCount(this.id);">My Counter</div></div></div>'));
divNumber++;
});
function makeCount(id){
var count = parseInt( $("#"+id).text());
if( isNaN(count) ){
count = 1; //For the first click
}else{
count++;
}
$("#"+id).text(count);
}
$(".GreyDiv").on("click", function() {
$(".container").css({display:'none'});
$(".List").css({display:'block'});
});
$(".RedDiv").on("click", function() {
$(".container").css({display:'block'});
$(".List").css({display:'none'});
});
.Wrap
{
width:650px;
height:800px;
}
.container
{
position:relative;
top:5px;
left:5px;
width:200px;
height:200px;
background-color:red;
float:left;
margin-left:5px;
margin-top:5px;
display:none;
}
.List
{
position:relative;
top:5px;
left:5px;
width:400px;
height:150px;
background-color:rgba(200,200,200,1);
float:left;
margin-left:5px;
margin-top:5px;
}
.AddDiv
{
position:absolute;
top:0px;
}
.GreyDiv
{
position:absolute;
top:0px;
left:170px;
}
.RedDiv
{
position:absolute;
top:0px;
left:250px;
}
.count
{
position:absolute;
width:100px;
height:100px;
position:absolute;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
background-color:white;
text-align:center;
line-height:100px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Wrap">
<div class="container">
<div class="count" id="div0" onclick="makeCount(this.id);">My Counter</div>
</div>
<div class="List">
<div class="count" id="div0" onclick="makeCount(this.id);">My Counter</div>
</div>
</div>
<button class="AddDiv">AddDiv</button>
<button class="GreyDiv">GreyDiv</button>
<button class="RedDiv">RedDiv</button>
Hello, I have problem with connect appropriate divs. I would like that if I click "MyCounter" will be count in GreyDiv and RedDiv the same number, but now it is countin separately. I would like that the grey and red will be the same div with different looks. And the last problem when RedDiv is active and i will click AddDiv and grey dic is going to show, but should add in the background
Thank you for your help and time
I've solved your ancient problem, two years passed and I think now this isn't problem for you, but maybe will be useful for someone else. I've completely changed your code, I use event delegation and a few if-else statements.
<div class="Wrap">
<div class="container">
<div class="Boxes">
<div class="count">My Counter</div>
</div>
</div>
</div>
<button class="AddDiv">AddDiv</button>
<button class="GreyDiv">GreyDiv</button>
<button class="RedDiv">RedDiv</button>
jQuery part:
let greyDiv = true;
let redDiv = false;
$('.AddDiv').on('click', function() {
if(greyDiv,greyDiv){
$('.Wrap').prepend($('<div class="container"><div class="Boxes" style="width:400px;height:150px;background-color:rgba(200,200,200,1)"><div class="count">My Counter</div></div></div>'));
} else {
$('.Wrap').prepend($('<div class="container"><div class="Boxes" style="width:200px;height:200px;background-color:red"><div class="count">My Counter</div></div></div>'));
}
});
$(document).on('click', function(e){
if(e.target.className === 'count'){
if(isNaN(e.target.textContent)){
e.target.textContent = 1
} else {
e.target.textContent++
}
}
})
$(".GreyDiv").on("click", function() {
greyDiv = true;
redDiv = false;
$(".Boxes").css({width:'400px',height:'150px',backgroundColor:'rgba(200,200,200,1)'});
});
$(".RedDiv").on("click", function() {
greyDiv = false;
redDiv = true;
$(".Boxes"). css({width:'200px',height:'200px',backgroundColor:'red'});
});
And a little changes in css:
.container{
position:relative;
top:5px;
left:5px;
float:left;
margin-left:5px;
margin-top:5px;
}
.Boxes{
width:400px;
height:150px;
background-color:rgba(200,200,200,1);
}
And here is a working fiddle: https://jsfiddle.net/dsm47frh/2/
Duplicate ID's is a bad idea. However you can have as many duplicate classes as you need so why not try
// replaces makeCount() function
$(".count").on("click", function(){
var num = parseInt($(this).text))
$(".count").html(num + 1)
})
What this does is to bind a click event to any existing or added-later element with class including 'count'. When any such element is clicked we get its text, convert to an integer then set the value of all elements of class='count' to that number + 1.
To implement this just replace it over the makeCount() function, and remove all the occurrences of
onclick="makeCount(this.id);
as this is no longer needed since we bound the click event as a listener on the class.
Related
var imgs = ["https://i.stack.imgur.com/mucrb.png",
"https://i.stack.imgur.com/0BH67.png",
"https://i.stack.imgur.com/KdNeR.png",
"https://i.stack.imgur.com/StOAl.png",
"https://i.stack.imgur.com/yhvqi.png"];
bs = document.getElementsByTagName("button");
for(var i =0;i<bs.length;i++){
bs[i].addEventListener("click",showImg);
}
pLeft =document.getElementById("left");
pLeft.addEventListener("click",prevImg);
pRight =document.getElementById("right");
pRight.addEventListener("click",nextImg);
function showImg(e){
x = e.target.getAttribute("order");
document.getElementById("loopImg").setAttribute("src",imgs[x-1]);
}
function nextImg(e){
x = e.target.getAttribute("order");
if(x == imgs.length-1){
x = 0;}
else{
x = x+1;}
document.getElementById("loopImg").setAttribute("src",imgs[x]);
}
function prevImg(e){
x = e.target.getAttribute("order");
if(x == 0){
x = imgs.length-1;}
else{
x = x-1;}
document.getElementById("loopImg").setAttribute("src",imgs[x]);
}
#main{
width:600px;
height:400px;
border:1px solid red;
display:grid;
grid-template-columns:60px auto 60px;
grid-template-rows:60px auto 60px;
grid-template-areas:"des des des"
"left loopImg right"
"buttons buttons buttons";
margin:0 auto;
}
#des{
grid-column: 1/4;
grid-row:1/2;
margin:auto;
}
#loopImg{
grid-column:2/3;
grid-row:2/3;
border:1px solid green;
margin:auto;
}
#left{
grid-column:1/2;
grid-row:2/3;
margin:auto;
}
#right{
grid-column:3/4;
grid-row:2/3;
margin:auto;
}
#buttons{
grid-column:1/4;
grid-row:3/4;
margin:auto;
}
button{
width:30px;
height:30px;
border:1px solid green;
border-radius:50%;
}
img{
width:200px;
height:200px;
}
<div id="main">
<div id="des">loop images</div>
<img id="loopImg" src="i1.png" alt="">
<p id="left"><</p>
<p id="right">></p>
<div id="buttons">
<button order="1" >1</button>
<button order="2" >2</button>
<button order="3" >3</button>
<button order="4" >4</button>
<button order="5" >5</button>
</div>
</div>
I want to write a loop images js script.
To click the button ,image can display according to the number in button.
Why nextImg and prevImg can't set elements's src attribution when to click them?
The nextImg can only work for one click, it can't run when to click for the second time.
The prevImg can't work at all.
It can get the order number when to click button key, how to get the order number when to click pLeft and pRight key?
The statement x = e.target.getAttribute("order"); in nextImg and prevImg can't get image's order number,how to fix it?
On the click of left and right, you are trying to get the arribute order of the clicked element. But actually it doesn't have any attribute like that..
What I have done is added a counter as to where is the current selected image. so whenever you click left or right, I decrement/increment the counter and set the image attribute with the waht the counter index says..
var imgs = ["https://i.stack.imgur.com/mucrb.png",
"https://i.stack.imgur.com/0BH67.png",
"https://i.stack.imgur.com/KdNeR.png",
"https://i.stack.imgur.com/StOAl.png",
"https://i.stack.imgur.com/yhvqi.png"];
bs = document.getElementsByTagName("button");
for(var i =0;i<bs.length;i++){
bs[i].addEventListener("click",showImg);
}
pLeft =document.getElementById("left");
pLeft.addEventListener("click",prevImg);
pRight =document.getElementById("right");
pRight.addEventListener("click",nextImg);
function showImg(e){
x = e.target.getAttribute("order");
document.getElementById("loopImg").setAttribute("src",imgs[x-1]);
currentImage = x-1
}
var currentImage = 0;
function nextImg(){
currentImage = (currentImage + 1) % 5
document.getElementById("loopImg").setAttribute("src",imgs[currentImage]);
}
function prevImg(){
if (currentImage === 0) {
currentImage = 4
}
else {
currentImage --;
}
document.getElementById("loopImg").setAttribute("src",imgs[currentImage]);
}
#main{
width:600px;
height:400px;
border:1px solid red;
display:grid;
grid-template-columns:60px auto 60px;
grid-template-rows:60px auto 60px;
grid-template-areas:"des des des"
"left loopImg right"
"buttons buttons buttons";
margin:0 auto;
}
#des{
grid-column: 1/4;
grid-row:1/2;
margin:auto;
}
#loopImg{
grid-column:2/3;
grid-row:2/3;
border:1px solid green;
margin:auto;
}
#left{
grid-column:1/2;
grid-row:2/3;
margin:auto;
}
#right{
grid-column:3/4;
grid-row:2/3;
margin:auto;
}
#buttons{
grid-column:1/4;
grid-row:3/4;
margin:auto;
}
button{
width:30px;
height:30px;
border:1px solid green;
border-radius:50%;
}
img{
width:200px;
height:200px;
}
<div id="main">
<div id="des">loop images</div>
<img id="loopImg" src="i1.png" alt="">
<p id="left"><</p>
<p id="right">></p>
<div id="buttons">
<button order="1" >1</button>
<button order="2" >2</button>
<button order="3" >3</button>
<button order="4" >4</button>
<button order="5" >5</button>
</div>
</div>
prevImg and nextImg don't work because:
Those elements don't have an order attribute, so you get null from e.target.getAttribute("order"), and
In the case of nextImg, if it did have the attribute, its value would be a string, so x = x + 1 would be string concatenation, not addition.
Instead, maintain the current index in a variable, see *** comments:
var imgs = ["https://i.stack.imgur.com/mucrb.png",
"https://i.stack.imgur.com/0BH67.png",
"https://i.stack.imgur.com/KdNeR.png",
"https://i.stack.imgur.com/StOAl.png",
"https://i.stack.imgur.com/yhvqi.png"];
var bs = document.getElementsByTagName("button"); // *** Added var
for(var i =0;i<bs.length;i++){
bs[i].addEventListener("click",showImg);
}
var pLeft =document.getElementById("left"); // *** Added var
pLeft.addEventListener("click",prevImg);
var pRight =document.getElementById("right"); // *** Added var
pRight.addEventListener("click",nextImg);
var currentIndex = 0; // ***
// *** Reusable function so we aren't repeating ourselves constantly below
function displayImage(src) {
// *** Notice the .src property
document.getElementById("loopImg").src = src;
}
displayImage(imgs[0]); // *** Show the first image
function showImg(e){
// *** Note the unary + to convert to number
currentIndex = +e.target.getAttribute("order") - 1;
displayImage(imgs[currentIndex]);
}
function nextImg(e){
currentIndex = (currentIndex + 1) % imgs.length; // *** Wraps around
displayImage(imgs[currentIndex]);
}
function prevImg(e){
currentIndex = (currentIndex - 1 + imgs.length) % imgs.length; // *** Wraps around
displayImage(imgs[currentIndex]);
}
#main{
width:600px;
height:400px;
border:1px solid red;
display:grid;
grid-template-columns:60px auto 60px;
grid-template-rows:60px auto 60px;
grid-template-areas:"des des des"
"left loopImg right"
"buttons buttons buttons";
margin:0 auto;
}
#des{
grid-column: 1/4;
grid-row:1/2;
margin:auto;
}
#loopImg{
grid-column:2/3;
grid-row:2/3;
border:1px solid green;
margin:auto;
}
#left{
grid-column:1/2;
grid-row:2/3;
margin:auto;
}
#right{
grid-column:3/4;
grid-row:2/3;
margin:auto;
}
#buttons{
grid-column:1/4;
grid-row:3/4;
margin:auto;
}
button{
width:30px;
height:30px;
border:1px solid green;
border-radius:50%;
}
img{
width:200px;
height:200px;
}
<div id="main">
<div id="des">loop images</div>
<img id="loopImg" src="" alt="">
<p id="left"><<!-- *** Note using entity for '<' --></p>
<p id="right">></p>
<div id="buttons">
<button order="1" >1</button>
<button order="2" >2</button>
<button order="3" >3</button>
<button order="4" >4</button>
<button order="5" >5</button>
</div>
</div>
Side note: I didn't do a full audit of the code or anything like that. I did notice that in multiple places, the original code was falling prey to what I call The Horror of Implicit Globals. Be sure to declare your variables (bs, x, pLeft, pRight), in the narrowest scope you can.
The Issue
I have a shopping cart for an online store and to view the contents of the shopping bag you hover over a div in the navigation menu. I made a prototype where the shoppingTab div actually touched the trolley div in the navigation bar that made it appear upon hovering. This then allowed me to move my cursor from the shoppingTab div in the navigation bar to the trolley div without the shopping cart disappearing until onmouseout which was strangely set only to the shoppingTab in the navigation bar, not the trolley div itself but I liked this odd little quirk. Therefore I would like to replicate this behaviour on to my new site.
Don't worry: I know what you've read up to this point hasn't been enough information to go off, don't worry there is more detailed stuff sitting below above my current code. You'll get what I mean when you scroll further down :).
PROTOTYPE CODE
Here is the prototype on JSFiddle (and it doesn't work onmouseover???) https://jsfiddle.net/Please_Reply/k1k566wp/1/ so just in case here is the raw code which will work if you copy and paste it into a blank HTML file etc.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.container{
width:960px;
margin:auto;
}
.header{
width:960px;
height:100px;
background-color:#06F;
float:left;
}
#trolley{
width:150px;
height:30px;
background-color:white;
float:right;
border-radius:10px;
color:black;
border:1px solid black;
line-height:30px;
font-family:"Calibri";
cursor: pointer;
}
.shop{
width:960px;
height:700px;
background-color:white;
float:left;
font-family:"Calibri Light";
padding:20px;
}
#shoppingTab{
display:none;
height:400px;
width:400px;
background-color:#CCC;
color:black;
position:relative;
margin-top:1px;
border-radius:10px;
color:black;
border:1px solid black;
padding-left:10px;
float:right;
}
html{
background-color:#00F;
}
.product{
height:200px;
width:150px;
float:left;
border: 1px solid black;
border-radius:10px;
margin-right:20px;
font-size:16px;
text-align:center;
cursor:pointer;
}
.product:hover{
border:1px solid blue;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<span id="name"></span><div id="trolley" onmouseover="tabDisplay('block')" onmouseout="tabDisplay('none')"><center>Shopping Cart <span style='font-family:webdings'>¤</span> <span id="NOI" style="background-color:red; border-radius:360px; color:white; padding-left:5px;padding-right:5px">0</span></center>
<div id="shoppingTab">You have selected <span id="NOI2">0</span> items. Your total is $<span id="totalPrice">0</span><br/><span id="itemsList"></span></div>
</div>
</div>
<div class="shop" style="font-size:28px">Welcome, <span id="name2"></span>.<hr /><br/>Products<br/><hr />
<div class="product" onclick="addToCart('sunglasses', 0, 70)">Pair of sunglasses ($70)<br /><br /><span onclick="change(1)">Click to add to cart</span></div>
<div class="product" onclick="addToCart('shoes', 1, 180)">Pair of shoes ($180)<br /><br /><span onclick="change(3)">Click to add to cart</span></div>
<div class="product" onclick="addToCart('belt', 2, 20)">A belt ($20)<br /><br /><span onclick="change(3)">Click to add to cart</span></div>
</div>
</div>
</body>
</html>
<script>
var customerName = "";
var numberOfItems = 0;
var total = 0;
var items = [];
var stat = []
for(var a = 1; a <= 3; a++){
stat[a] = false;
}
function update(){
document.getElementById("NOI").innerHTML = numberOfItems;
document.getElementById("NOI2").innerHTML = numberOfItems;
document.getElementById("totalPrice").innerHTML = total;
document.getElementById("itemsList").innerHTML = items.join("<br />");
}
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
function addToCart(productName, productID, price){
items[productID] = productName;
total += price;
numberOfItems++;
update();
}
function removeFromCart(productName, productID, price){
items.splice(productID, 1);
total -= price;
if(stat[productID]){
numberOfItems--;
}
update();
}
function change(i){
if(stat[i] == false){
stat[i] = true;
}else{
stat[i] = false;
}
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("customer");
if (user != "") {
customerName = getCookie("customer");
document.getElementById("name").innerHTML = customerName;
alert("Welcome again, " + user + ".");
} else {
document.getElementById("name").innerHTML = "please set up an account";
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("customer", user, 30);
document.getElementById("name").innerHTML = user;
}
}
}
function changeCookie(){
var user = getCookie("customer");
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("customer", user, 30);
}
document.getElementById("name").innerHTML = user;
}
checkCookie();
</script>
MY CURRENT CODE
I have a JSFiddle of my current code (Which doesn't work so I copied the code below as well. I think it is because I have pure Javascript in there which it is trying to read as JQuery??? I don't know... anyway if you can't fix the JSFiddle just copy the code that actually works below the JSFiddle link)... https://jsfiddle.net/Please_Reply/9uwj2bed/2/
So basically, in the code below, I need the shoppingCart div to appear when you hover over the shopcartbar div (probably using onmouseover). But in terms of onmouseout, I would like to be able to hover onto the shoppingCart div without it disappearing. I would like the onmouseout to work on both the shopcartbar div and the shoppingCart div just like it somehow does in my prototype???
One other issue when I use onmouseover on the shoppingCart div is that when I hover over any of the .smallProduct divs inside of the shoppingCart div, they seem to trigger onmouseout which is not what I want either, they are part of the shoppingCart div.
<head>
<style>
body{ /* Applies to the <body> tag */
margin:0px; /* Sets the margin on all sides to 0px */
}
.container{ /* The container class */
width:100%; /* This sets the width */
height:100%; /* This sets the height */
background-color:white; /* Sets the background colour */
font-family:"Myriad Pro"; /* Sets the font family */
}
.header{ /* The header class */
width:100%;
background-color:blue;
color:white; /* The sets the colour of the font */
}
div{
display: inline-block; /* Sets the display type */
float:left; /* Sets the float position */
}
#one, #two, #three, #four{
background-color:black;
height:90px;
color:white;
text-align:center;
font-size:25px;
}
#slider{
background-color:blue;
height:10px;
width:100px;
position: absolute; /* Sets the position to a specific type */
left: 0; /* Sets the number of pixels from the left that this object is placed */
bottom:0; /* Sets the number of pixels from the bottom that this object is placed */
}
.inside{
margin-left:30px; /* Specifies the margin from the left side */
margin-right:30px; /* Specifies the margin from the right side */
padding-top:7px; /* Specifies the padding from the top side */
pointer-events:none; /* Specifies the cursor events */
margin-top:25px; /* Specifies the margin from the top side */
}
#shoppingTab{
display:none;
height:670px;
width:400px;
background-color:white;
color:black;
position:relative;
margin-top:-2px;
border-radius:10px;
color:black;
border:1px solid #323232;
padding:10px;
float:right;
z-index:50;
}
.smallProduct{
height:50px;
width:390px;
float:left;
border: 2px solid black;
border-radius:10px;
font-size:16px;
cursor:pointer;
margin-bottom:10px;
overflow:hidden;
}
.smallProduct:hover{
border:2px solid blue;
}
</style>
</head>
<body>
<div class="container"> <!-- This is the container -->
<div class="header"> <!-- This is the header -->
<div style="float:left"> <!-- This is the logo -->
<img src="logo.png" height="120px"/>
</div>
<div style="float:right; font-family:'Myriad Pro'; background-image:url(images/loginsignupbar.png); width:535.1px; height:30px">
<div onmouseover="tabDisplay('block')" id="shopcartbar" style="float:right; font-size:24px; margin-top:-7px">
<img src="images/shoppingCart.png" height="30px"/> Shopping Cart (<span id="numberOfItems">0</span>)
</div>
<div id="shoppingTab" onmouseout="tabDisplay('none')">
Shopping Cart<br />
<div class="smallProduct" style="margin-top:5px" id="thmbproduct0"></div>
<div class="smallProduct" id="thmbproduct1"></div>
<div class="smallProduct" id="thmbproduct2"></div>
<div class="smallProduct" id="thmbproduct3"></div>
<div class="smallProduct" id="thmbproduct4"></div>
<div class="smallProduct" id="thmbproduct5"></div>
<div class="smallProduct" id="thmbproduct6"></div>
<div class="smallProduct" id="thmbproduct7"></div>
<div class="smallProduct" id="thmbproduct8"></div>
Total: $<span id="totalPrice">00</span>.00
</div>
<span id="topnavbar" style="float:right; font-size:24px; margin-top:5.5px">
</span>
</div>
<div style="float:right; clear:right"> <!-- This is the navigation menu -->
<div style="position:relative"> <!-- This is the container of the navigation menu -->
<div id="slider"></div> <!-- This is the slider bar -->
<div id="one" class="item"><div class="inside">Button 1</div></div> <!-- This is just one of the buttons -->
<div id="two" class="item"><div class="inside">Button 2</div></div>
<div id="three" class="item"><div class="inside">Button 3</div></div>
<div id="four" class="item"><div class="inside">Button 4</div></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
</script>
<script type="text/javascript" src="./jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#slider").animate({
"left": $('#three').position().left + "px",
"width": $('#three').width() + "px"
}, 0);
$(".item").hover(function() {
$("#slider").stop();
$("#slider").animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);
});
$(".item").on("mouseout", function() {
$("#slider").stop();
$("#slider").animate({
"left": $('#three').position().left + "px",
"width": $('#three').width() + "px"
}, 500);
});
});
</script>
Try replacing this section:
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
With this:
$( "#shopcartbar, #shoppingTab" ).mouseenter(function() {
$("#shoppingTab").show();
})
.mouseleave(function() {
$("#shoppingTab").hide();
});
*Update 2
I discovered that the images were not fading in/out as they were not deemed as loaded, to resolve the issue I added the first 3 lines of jQuery code. I'm sure this can refactored, so will update when I have done so.
JSFiddle
HTML
<div class="gallery">
<div class='thisImg activeImg'><img src='img/hair/hair-colour-5.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-1.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-2.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-3.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-4.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-6.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-7.jpg' /></div>
<div class='thisImg'><img src='img/hair/hair-colour-8.jpg' /></div>
<div class='nextImg'><p><a>></a></p></div>
<div class='prevImg'><p><a><</a></p></div>
</div>
CSS
.gallery {
position:absolute;
top:2px;
right:0;
float:right;
height:400px;
width:400px;
border:3px solid #CFC;
}
.thisImg {
overflow:hidden;
position:absolute;
top:0;
left:0;
display:hidden;
}
.activeImg {
display:block;
z-index:2;
}
.prevImg, .nextImg {
position:absolute;
background-color:#CFC;
box-shadow: inset 0 0 10px #9C0;
-moz-box-shadow: inset 0 0 10px #9CO;
-webkit-box-shadow: inset 0 0 10px #9CO;
text-align:center;
top:175px;
height:50px;
width:50px;
font-size:42px;
z-index:2;
opacity:0.5;
}
.prevImg {
left:10px;
}
.nextImg {
right:10px;
}
.nextImg p, .prevImg p {
position:absolute;
left:15px;
top:-5px;
color:#630;
}
.nextImg:hover, .prevImg:hover {
opacity:1;
color:#630;
display:block;
cursor:pointer;
}
jQuery
$(document).ready(function() {
$(".thisImg").hide();
$(".activeImg").show();
$("#thisImg").bind("load", function () { $(this).fadeIn(); });
});
var main = function() {
$('.nextImg').click(function() {
var currentImg = $('.activeImg');
var nextImg = currentImg.next(".thisImg");
if(nextImg.length == 0) {
nextImg = $('.thisImg').first();
}
currentImg.fadeOut(3000).removeClass('activeImg');
nextImg.fadeIn(3000).addClass('activeImg');
});
$('.prevImg').click(function() {
var currentImg = $('.activeImg');
var prevImg = currentImg.prev(".thisImg");
if(prevImg.length == 0) {
prevImg = $('.thisImg').last();
}
currentImg.fadeOut(3000).removeClass('activeImg');
prevImg.fadeIn(3000).addClass('activeImg');
});
}
$(document).ready(main);
http://jsfiddle.net/73geyvwd/1/ - working fiddle
Two main issues.
1.) You aren't setting a default "activeImg" element.
<div class="thisImg activeImg">
2.) Your .prev() and .next() methods need to include a .thisImg class selector, since you have other elements at a sibling level.
var nextImg = currentImg.next(".thisImg");
var prevImg = currentImg.prev(".thisImg");
I'm trying to make a pop up box, which gets invoked on clicking a button, this is what I've got so far.. http://jsfiddle.net/WGPhG/2/
Here is a fiddle that actually does what you want - http://jsfiddle.net/WGPhG/6/
JS
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.innerHTML = 'close';
cancel.onclick = function (e) { popup.parentNode.removeChild(popup) };
var message = document.createElement('span');
message.innerHTML = "This is a test message";
popup.appendChild(message);
popup.appendChild(cancel);
document.body.appendChild(popup);
}
NOTES
To set the class on an element you use element.className instead of element.class.
For the onclick event handler on the cancel element, it is better to directly assign the onclick handler with an anonymous function that does what you need as in my example above.
EDIT (More Efficient Way)
This is actually a much better of getting the results that you want because there is no overhead involved with recreating the elements every time the popup is shown. Fiddle - http://jsfiddle.net/WGPhG/7/
CSS
.popup
{
position:absolute;
top:0px;
left:0px;
margin:100px auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
display:none
}
.cancel
{
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
JS
function openPopup() {
document.getElementById('test').style.display = 'block';
}
function closePopup() {
document.getElementById('test').style.display = 'none';
}
Try this update on JSFiddle
Changed :
Center page (fixed).
effect (fadein and fadeout)
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup" style="display:none;">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
CSS
.popup {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
margin:auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
}
.cancel {
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
.cancel:hover {
background:rgb(255,50,50);
}
JS
function openPopup() {
//document.getElementById('test').style.display = 'block';
$('#test').fadeIn(1000);
}
function closePopup() {
//document.getElementById('test').style.display = 'none';
$('#test').fadeOut(500);
}
Try This
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.setAttribute('onClick', 'document.getElementById("test").parentNode.removeChild('+popup +');')
popup.innerHTML = "This is a test message";
document.body.appendChild(popup);
popup.appendChild(cancel);
}
I've updated your Fiddle and made it work.
The changed HTML...
<button id="popupButton">click here</button>
Updated JavaScript...
document.onreadystatechange = function () {
function popUp() {
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
popup.innerHTML = "This is a test message";
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.onclick= function () { popup.destroy(); }
popup.appendChild(cancel);
document.body.appendChild(popup);
}
document.getElementById('popupButton').onclick = popUp;
}
Did this answer your question or is there anything else?
Update Improved the code and the fiddle. Now open and close works
I'm very new with Javascript.
I'm trying to do something with Show/Hide functions.
html:
<html>
<head>
<title> New Document </title>
<style>
#button01 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button01:hover {
background-color:#ffcccc;
}
#button01 a {
display:block;
width:40px;
height:40px;
margin:auto;
background:url("button01.png")
}
#button01 a:hover {
width:40px;
height:40px;
background:url("button01-hover.png")
}
#hidden01 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #ffcccc;
}
#button02 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button02:hover {
background-color:#cccccc;
}
#button02 a {
display:block;
width:40px;
height:40px;
margin:auto;
background:url("button02.png")
}
#button02 a:hover {
width:40px;
height:40px;
background:url("button02-hover.png")
}
#hidden02 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #cccccc;
}
</style>
</head>
<body>
<div style="width:300px;">
<div id="button01"></div>
<div id="button02"></div>
</div>
<div id="hidden01"> </div>
<div id="hidden02"> </div>
</body>
</html>
script:
function toggle(offset){
var i, x;
var stuff = Array('hidden01', 'hidden02'); //put all the id's of the divs here in order
for (i = 0; i < stuff.length; i++){ //hide all the divs
x = document.getElementById(stuff[i]);
x.style.display = "none";
}
// now make the target div visible
x = document.getElementById(stuff[offset]);
x.style.display = "block";
window.onload = function(){toggle(0);}
}
That's working, but I want to fix 2 things:
1- Close/Hide hidden divs if I click on it's corresponding button;
2- After clicking a button, fix hover button image. If click again unfix;
I've tried almost all the scripts posted and can not find a solution. I don't want to open the divs at same time.
If opens one, close the others.
You're using jQuery, so use jQuery.
$(function() {
function toggle(offset) {
$('div[id^=hidden]').hide().eq(offset).show();
}
toggle(0);
});
I don't know what you mean by the two things you want to fix, however. Please clarify.
Edit
Okay, I see what you're going for now. I've cleaned up your code a lot.
HTML
<div style="width:300px;">
<div id="button1"><a></a></div>
<div id="button2"><a></a></div>
</div>
<div id="hidden1"> </div>
<div id="hidden2"> </div>
CSS
#button1, #button2 {
width:100px;
height:50px;
margin:10px;
padding:6px 0 0 0;
background-color:#f0f0f0;
}
#button1:hover {
background-color:#fcc;
}
#button2:hover {
background-color:#ccc;
}
#button1 a, #button2 a {
display:block;
width:40px;
height:40px;
margin:auto;
}
#button1 a {
background:url(http://lorempixum.com/40/40?1)
}
#button2 a {
background:url(http://lorempixum.com/40/40?3)
}
#button1 a:hover, #button1.hover a {
background:url(http://lorempixum.com/40/40?2)
}
#button2 a:hover, #button2.hover a {
background:url(http://lorempixum.com/40/40?4)
}
#hidden1, #hidden2 {
display:none;
width:300px;
height:200px;
margin:0 0 10px 0;
border:4px solid #fcc;
}
JavaScript
var $buttons = $('div[id^=button]'),
$hiddenDivs = $('div[id^=hidden]'),
HOVER_CLASS = 'hover';
$buttons.live('click', function() {
var $this = $(this),
i = $this.index();
$buttons.removeClass(HOVER_CLASS);
$this.addClass(HOVER_CLASS);
$hiddenDivs.hide().eq(i).show();
}).first().click();
Demo
Last edit
Changed JavaScript and CSS. http://jsfiddle.net/mattball/bNCNQ/
CSS
#button1:hover a, #button1.hover a {
background:url(...)
}
#button2:hover a, #button2.hover a {
background:url(...)
}
JS
$buttons.live('click', function () {
var $this = $(this),
i = $this.index(),
show = !$this.hasClass(HOVER_CLASS);
$buttons.removeClass(HOVER_CLASS);
$this.toggleClass(HOVER_CLASS, show);
$hiddenDivs.hide().eq(i).toggle(show);
});
Here's a working demo: http://jsfiddle.net/R6vQ4/33/.
All of your JavaScript code can be condensed into this little block (and this isn't even as small as it can get):
$(document).ready(function()
{
$('div[id^=button]').click(function()
{
var element = $('#hidden' + $(this).attr('id').substr(6));
$('div[id^=button]').css('cssText', 'background-color: none');
if (element.is(':visible'))
{
$(this).css('cssText', 'background-color: none');
$('div[id^=hidden]').hide();
} else {
$('div[id^=hidden]').hide();
element.show();
$(this).css('cssText', 'background-color: ' + $(this).css('background-color') + ' !important');
}
});
});
The state of the button "sticks" when you press it, but my technique is a bit hacky, so feel free to change it.
When you use jQuery, you actually use it ;)