JavaScript function on page load - javascript

I need to change the Div id "Div01" state to "highlight" class when the page loads.
Please see the code below:
HTML:
<div id="div01">user</div>
JS:
var role; function roleActive(obj){ if (role)
role.className = 'btn';
obj.className = 'highlight';
role = obj;}
CSS:
.btn{
display:block;
height:25px;
width:100px;
padding:5px 0px 0px 0px;
text-align:center;
font-size:16px;}
.highlight{
cursor:default;
display:block;
height:25px;
width:100px;
padding:5px 0px 0px 0px;
text-align:center;
font-size:16px;
background-color:#FFF;
border-bottom:4px solid #F0AB00;
color:#000;
text-decoration:underline;}
a.btn:link{background-color:#000;color:#FFF;}
a.btn:visited{background-color:#000;color:#FFF;}
a.btn:hover,active{background-color:#FFF;color:#000;text-decoration:underline; border-bottom:4px solid #F0AB00;}
Kindly help me to fix the problem.

Try
<script>
window.onload = function(){
roleActive(document.getElementById('div01').children[0]);
}
</script>

try this
window.onload = function(){
document.getElementById('div01').className = 'highlight'
}
or
<script>
document.getElementById('div01').className = 'highlight'
</script>
or
<script>
exampleCall();
function exampleCall()
{
document.getElementById('div01').className = 'highlight'
}
</script>

document.addEventListener('DOMContentLoaded', function(){
document.getElementById('div01').className = 'highlight';
}, false);

For Javascript:
window.onload = function() {
document.getElementById('div01').className = 'highlight';
}
For Jquery:
$(function() {
$('#div01').addClass('highlight');
});

Your onclick event is sending 'this' to the function, but it's the onclick event of the , not of the . Is this what you intended?
Since you're not using the inherent click functionality of the then I'd suggest getting rid of it. Just have the click event on the , so clicking it will fire roleActive() and apply the classes appropriately.

Related

How to detect which button is clicked in javascript?

im trying to figure out how to carry the id of the button when clicked to my function. 1 function to change color on mouseover and one function to change it back to original color when mouseout. i know i can do it simply in css but i just want to learn how to do it in javascript.
Thanks in advance.
Below is my code.
var buttonClass = this.className();
// document.getElementById("mainTitle");
this.style.backgroundColor="#000000";
this.style.color="#ffffff";
this.style.cursor = "pointer";
}
function defaultColor() {
var buttonClasss = this.getElementById();
//document.getElementById("addList");
this.style.backgroundColor = "#ffffff";
this.style.color = "#000000";
this.style.cursor = "pointer";
}
//event listener for Change Title button
document.getElementById("mainTitle").addEventListener("mouseover", changeColor);
document.getElementById("mainTitle").addEventListener("mouseout", defaultColor);
document.getElementById("mainTitle").addEventListener("click", changeTitle);
//event listener for change title ends here
//event listener for add listing
document.getElementById("addList").addEventListener("mouseover", changeColor);
document.getElementById("addList").addEventListener("mouseout", defaultColor);
document.getElementById("addList").addEventListener("click", addListing);
//event listener for add listing ends here
#mainTitle {
border:1px solid #ff33f4;
float:left;
clear:both;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}
#addList {
border:1px solid #ff33f4;
float:right;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}
#main {
clear:both;
margin-top:120px;
}
<div id="mainTitle" class="changeTitle">Change Title</div>
<div id="addList" class="addList">Add List</div>
Every event registered will comes with argument Event.
function defaultColor(e) {
// ^ argument (Event)
var currentClickedButton = e.currentTarget; // to get the current clicked button
/* Your code here */
}
When you attach a function to an event, you don't really need to track the id of the element emitting the event, you just need to use the 'this' keyword to access it. Below is a sample of this using your sample code.
<html>
<head>
<style>
#mainTitle {
border:1px solid #ff33f4;
float:left;
clear:both;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}
#addList {
border:1px solid #ff33f4;
float:right;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}
#main {
clear:both;
margin-top:120px;
}
</style>
<script type="text/javascript">
function defaultColor() {
//var buttonClasss = this.getElementById();
//document.getElementById("addList");
this.style.backgroundColor = "#ffffff";
this.style.color = "#000000";
this.style.cursor = "pointer";
}
function changeColor(){
this.style.backgroundColor="#000000";
this.style.color="#ffffff";
this.style.cursor = "pointer";
}
function changeTitle(){
}
function addListing(){
}
function OnL(){
//event listener for Change Title button
document.getElementById("mainTitle").addEventListener("mouseover", changeColor);
document.getElementById("mainTitle").addEventListener("mouseout", defaultColor);
document.getElementById("mainTitle").addEventListener("click", changeTitle);
//event listener for change title ends here
//event listener for add listing
document.getElementById("addList").addEventListener("mouseover", changeColor);
document.getElementById("addList").addEventListener("mouseout", defaultColor);
document.getElementById("addList").addEventListener("click", addListing);
}
</script>
</head>
<body onload="OnL()">
<div id="mainTitle" class="changeTitle">Change Title</div>
<div id="addList" class="addList">Add List</div>
</body>
</html>

Is there a Better way to handle Same callback function but different input params?

I have a callback function to delete an li element.
function deleteLi(liElement) {
liElement.remove()
}
Two buttons does the same operation. On hovering the liElement, I get a edit & delete option. On clicking the edit option, it opens a dialog which also has a delete option. So both the buttons, does the same and hence I am calling the same function.
But it looks like this
$('.edit').on('click', function() {
currentField = $(this).parents('li');
openDialog();
});
$('.delete1').on('click', function() {
deleteLi($(this).parents('li'));
});
$('.delete2').on('click', function() {
deleteLi(currentField)
});
So is there any other best way to handle this?
You can simply give a single class to both delete button 'delete1' and use following code
$('.delete1').on('click', function() {
deleteLi($(this).parents('li'));
});
If your css if different for that delete button then multiple class selector in jQuery.
Edited the code as per the comments:
$('.delete1, .delete2').on('click', function() {
if(currentField == null) {
currentField = $(this).parents('li');
}
deleteLi(currentField);
});
With this HTML:
<ul class="editableList">
<li>
<span>Stuff here</span>
-
e
</li>
<li>
<span>Other stuff here</span>
-
e
</li>
</ul>
And this J:
$('.editableList').on('click', '.delete', function(e){
e.preventDefault();
$(this).parent('li').remove()
}).on('click', '.edit', function(e){
e.preventDefault();
editLi(this);
});
function editLi(elt) {
// Code to edit "li > span" element
console.log('editing element', elt);
}
You can avoid thee global variable by adding a class (or a data attribute, i'm using a class here for the visual feedback) to the selected <li> on click of edit, and remove it once you close the edit popup:
$('.edit').on('click', function () { // open edit popup
$(this).closest('li').addClass("active"); // mark the current <li>
$("#editPopup").show();
});
$("#editPopup span").on("click", function () { // close edit popup
$(".active").removeClass("active"); // unselect it
$("#editPopup").hide();
});
$('.delete').on('click', function () { // inline delete option
$(this).closest('li').remove();
});
$('#delete').on('click', function () { // delete option in popup
$(".active").remove();
$("#editPopup").hide();
});
* {
margin:0;
padding:0;
}
ul {
list-style-type:none;
}
li {
border-bottom:1px solid;
background:silver;
height:50px;
line-height:50px;
}
li a {
display:none;
float:right;
margin:0 5px;
}
li:hover a {
display:inline-block;
}
li.active {
background:dodgerblue;
}
#editPopup {
display:none;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:200px;
height:50px;
margin:auto;
background:#fff;
box-shadow:0px 0px 5px 0px rgba(0, 0, 0, 0.5);
}
#editPopup span {
position:absolute;
right:5px;
cursor:pointer;
color:red;
}
#editPopup a {
margin:5px;
vertical-align:bottom;
}
li:first-child span{
padding:3px;
font-family: arial;
font-size: 14px;
color:#0077CC;
outline:1px solid grey;
background:white;
}
li:first-child span:hover{
text-decoration:underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="editableList">
<li> The <span>Full page</span> button is messing with my options!
x
edit
</li>
<li> <span>Item 2</span>
x
edit
</li>
<li> <span> Hover Me!</span>
x
edit
</li>
</ul>
<div id="editPopup"> <span>x</span><br/>
edit
delete
</div>
I'd use callback approach. When Edit button is hit, you define the currentField variable, and then define anonymous callback, which is called from openDialog's deleteButton.
$('.delete1').on('click', function () {
deleteLi($(this).parents('li'));
});
$('.edit').on('click', function () {
var currentField = $(this).parents('li');
openDialog({
onDelete: function () {
deleteLi(currentField);
}
});
});
function openDialog(args) {
//... open dialog here ...
$('.delete2').on('click', args.onDelete);
}

Custom confirmbox, wait for button click in function Javascript

I want to make a confirmbox that returns true or false. If the user clicks OK it has to return true and if the user clicks Cancel or the cross in the upperleft corner it has to return false. But I'm stuck at the point the user clicks the button. I've already tried using callbacks but it could not help me to achieve what I would like to have.
So far I have this:
Fiddle
function SimpleAlert( title, text, cancel)
{
var stylesheet = document.createElement('style');
stylesheet.id="SimpleAlertStylesheet";
stylesheet.innerHTML="#SimpleAlertOverlay { top:0px; bottom:0px; left:0px; right:0px; position:fixed; background:rgba(230,230,230,0.5); height:100%; width:100%; font-family:Sans-serif; } #SimpleAlertLightbox { background:#f5f5f5; border-radius:3px; width:400px; box-shadow: 0px 0px 15px rgba(0,0,0,0.3); } .SimpleAlertTopbar { border-radius:3px; background:#e5e5e5; height:24px; color:#444; line-height:24px; padding:0px 5px; font-weight:bold; font-size:14px; border-bottom:1px solid #DDD } .SimpleAlertCross1 { margin:5px 15px 0px 0px; opacity:0.7; } .SimpleAlertCross2 { margin:5px 15px 0px 0px; opacity:0.5; } .SimpleAlertCross1:hover { opacity:1; } .SimpleAlertTopbar > div { float:left } .SimpleAlertMessagediv { padding:20px 40px; font-size:14px; color:#444; } .SimpleAlertButtondiv { height:26px; line-height:26px; padding:0px 40px 18px 40px; } .SimpleAlertButtondiv button { height:26px; background:#f9f9f9; border:1px solid #CCC; color:#444; float:right; } .SimpleAlertButtondiv button:hover { border:1px solid #AAA; } .SimpleAlertButtondiv button:focus { outline:none; }";
var overlay = document.createElement('div');
overlay.id = 'SimpleAlertOverlay';
var lightbox = document.createElement('div');
lightbox.id = 'SimpleAlertLightbox';
overlay.appendChild(lightbox);
var topbar = document.createElement('div');
topbar.setAttribute("class", "SimpleAlertTopbar");
lightbox.appendChild(topbar);
var crossdiv = document.createElement('div');
topbar.appendChild(crossdiv);
var crossspan = document.createElement('span');
crossdiv.appendChild(crossspan);
var cross = document.createElement('img');
if(cancel)
{
cross.setAttribute("class", "SimpleAlertCross1");
}
else
{
cross.setAttribute("class", "SimpleAlertCross2");
}
cross.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDBGMDEwRUNCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDBGMDEwRURCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0MEYwMTBFQUJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0MEYwMTBFQkJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp1kTM8AAAFGSURBVHjalJI9S0JRGMd/VwKnbKkQvOpUBqIOOrj4DTTEanKqzSGQvknt9gXiIgp+BScXdZEKB18GockGscHTc7zdazcs8g+/w3l5nvM/L4+hlMJVKnUo7Z2QF06/ZgdCU3ig231zQg03MZm8kLYmHLBdc+GGXs/aJCYSOulJj/lb2uWKft8yVDx+JINXIcD/pJ1PfKxWt0JAYE2pBJWK3c9moVqFYBB33Y6t+lDqHH1ch3YbTBPKZSgUYDaD6RRPjFJ57Xj2bTcYj6HTgXQalktoNPCs28T21p2fWiw2fSfYqw/tOPDsFgpBLme7+v1QLG5zHOrEpmdS320uD1eTL63XIZOxj+1NbBkqGj0W65ddv8MugEhktwIYjaxNyYXDl9I+Cvu/JL0L1/LqlrdWtUzTKXL5QGL69YRnoSXcM5m4Rf4pwABHDba2DxAS7QAAAABJRU5ErkJggg==';
crossspan.appendChild(cross);
var titlediv = document.createElement('div');
titlediv.innerHTML = title;
topbar.appendChild(titlediv);
var messagediv = document.createElement('div');
messagediv.setAttribute("class", "SimpleAlertMessagediv");
messagediv.innerHTML = text;
lightbox.appendChild(messagediv);
var buttondiv = document.createElement('div');
buttondiv.setAttribute("class", "SimpleAlertButtondiv");
lightbox.appendChild(buttondiv);
var okbutton = document.createElement('button');
okbutton.innerHTML="OK";
buttondiv.appendChild(okbutton);
document.body.appendChild(overlay);
document.body.appendChild(stylesheet);
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
function CenterDiv(elementId){
var main = document.getElementById(elementId);
var wi=main.offsetWidth;
var he=main.offsetHeight;
var marginleft = wi / 2;
var margintop = he / 2;
main.style.marginLeft="-" + marginleft;
main.style.marginTop="-" + margintop;
main.style.position="absolute";
main.style.left="50%";
main.style.top="50%"
}
CenterDiv('SimpleAlertLightbox');
if(cancel)
{
var cancelbutton = document.createElement('button');
cancelbutton.innerHTML="Cancel";
cancelbutton.style.marginRight="30px";
buttondiv.appendChild(cancelbutton);
cancelbutton.addEventListener('click', SimpleAlertCancel , false);
}
cross.addEventListener('click', SimpleAlertCancel , false);
okbutton.addEventListener('click', SimpleAlertOK , false);
function SimpleAlertCancel()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
function SimpleAlertOK()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
}
What I'm trying to achieve is:
if(SimpleAlert('title', 'text', true))
{
//User clicked OK
}
else
{
//User clicked Cancel
}
I am looking for something like the system functions: alert(), confirm() and prompt(). These functions pause all Javascript and wait until a button has been clicked.
I have browsed throught all the folders of the internet browsers installed on my computer to find the above functions declared but i couldn't find them.
Here is an image of the alertbox for the person that doesn't open the fiddle ;-)
I hope you can help me to get a step closer.
You can't do that with Javascript, as it is asynchronous, the code continues executing even if the window/div is shown.
For managing the actions, execute the code you need on the onclick events on each of the "OK" and "Cancel" buttons

javascript onclick create(element) div viz popup box

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

Show / Hide / Toggle - Javascript / jQuery

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 ;)

Categories