When hovering over text, change the text and background image - javascript

I am new to coding and wrapping my head around utilization of JavaScript it still hard for me.
My problem is that I have like a navigation menu, those have one word in them. I want that when I hover over navigation menu background of the entire site changes corresponding to the navigation menu item I hovered over, and the navigation item changes it's content from one word to more words.
I tried searching on Google, YouTube and here on stackoverflow of course. I managed to get working code but it feels like a mess and bad practice and I wasn't able to implement good answers to my code or they were using ES5 JavaScript which differentiates from ES6 a lot.
Here are the things I tried:
1 . First thing i tried is to create a function with if statements. Didn't quite work. Probably because of my low understanding of JS.
I tried then to addEventListener to every navigation menu item individually. And that works, but it's a mess. Just blocks of copy / pasted code.
I tried then to create a function again and have onmouseover = "function()" inside of HTML but didn't work either.
Then I tried to do it over CSS but my inexperience started to show again it seems. I wasn't able to succeed in it with :before and :after either.
I have some example code here.
<div id='bckgimg'>
<div class="nav-container">
<a href='/nav1' id='nav-nav1' class='nav'>NAV1</a>
<a href='/nav2' id='nav-nav2' class='nav'>NAV2</a>
<a href='/nav3' id='nav-nav3' class='nav'>NAV3</a>
<a href='/nav4' id='nav-nav4' class='nav'>NAV4</a>
</div>
</div>
<style>
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
}
</style>
<script>
const nav1 = document.getElementById('nav-nav1');
const nav2 = document.getElementById('nav-nav2');
const nav3 = document.getElementById('nav-nav3');
const nav4 = document.getElementById('nav-nav4');
const bckgImg = document.getElementById("bckgimg");
// repeat this code 3 more times with nav2, nav3, nav4
// code bellow checks if <div> is hovered over and changes background image <div> + changes text of the <div>
navStories.addEventListener('mouseenter', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/2/300/200')";
navStories.innerHTML = "MY NAV 1 LONGER";
});
// if <div> is hovered out it returns the original picture to background <div> and original text of <div>
navStories.addEventListener('mouseleave', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
navStories.innerHTML = "NAV1";
});
</script>

Alright figured it out! Took me whole day but I got it!
First of, on JSfiddle where it says JavaScript + No-Library (pure JS) you need to press on the arrow on the side and for LOAD TYPE choose no wrap - bottom of body.
Second, if you have code which has an error which is represented by red color by JSfiddle your whole directory (JavaScript directory in my case) won't run. Error in my code was that I just commented all the code I didn't need at the bottom with /* but didn't close it since I thought it wasn't important.
Third, the solution itself:
// changed whole thing, which was my point. Reduced code from ~50 lines to two functions in 16 lines
// onHover function has a property of i which corresponds to numbers in html on onmouseover and out
// created arrays with IDs, what text and image should be after hovering
// i will correspond to numbers in html which in turn correspond to numbers in arrays
function onHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["MY NAV 1 LONGER", "MY NAV 2 LONGER", "MY NAV 3 LONGER", "MY NAV 4 LONGER"];
const bckgUrls = ["url('https://picsum.photos/id/2/300/200", "url('https://picsum.photos/id/3/300/200')", "url('https://picsum.photos/id/4/300/200')", "url('https://picsum.photos/id/5/300/200')"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = `${bckgUrls[i]}`;
}
// when hovering out from text do same like onHover just the reverse
// return values of navigation menu and background image to original
function outHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["NAV1", "NAV2", "NAV3", "NAV4"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
}
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
overflow: hidden;
background-position: center center;
background-size: cover;
height: 300px;
}
a {
color: white;
text-decoration: none;
}
<div id='bckgimg'>
<!-- because we changed ON LOAD options now onmouseover and on mouseout will pull functions from JS -->
<div class="nav-container">
<a onmouseover="onHover(0)" onmouseout="outHover(0)" href='/nav1' id='nav-nav1' class='nav'>NAV1</a><br>
<a onmouseover="onHover(1)" onmouseout="outHover(1)" href='/nav2' id='nav-nav2' class='nav'>NAV2</a><br>
<a onmouseover="onHover(2)" onmouseout="outHover(2)" href='/nav3' id='nav-nav3' class='nav'>NAV3</a><br>
<a onmouseover="onHover(3)" onmouseout="outHover(3)" href='/nav4' id='nav-nav4' class='nav'>NAV4</a><br>
</div>
</div>

Related

Toggle many classes

so thanks for you all that help me. You made me think what i was doing, so i short my code in what i thought would be good, but before the code was long but working now, short but not works with the first panel even that there is no errors.So maybe a loop?
So the html goes like this:
<div class="container">
<div class="down sound">
<img id="batman" class="image-1-panel active" src="flash.svg">
<img class="image-2-panel notactive" src="http://cdn.playbuzz.com/cdn/3c096341-2a6c-4ae6-bb76-3973445cfbcf/6b938520-4962-403a-9ce3-7bf298918cad.jpg">
<p class="image-3-panel notactive">Bane</p>
<p>Joker</p>
<p>Alfred</p>
</div>
And then it repeats for 3 more containers like that one. On css for the active and not active i have:
.notactive{
visibility: hidden;
position: relative;
}
.active{
position: absolute;
}
And in js:
document.querySelector('#batman').addEventListener('click', batman);
function batman(){
document.querySelector('.image-1-panel').classList.toggle('.notactive');
document.querySelector('.image-1-panel').classList.toggle('.active');
document.querySelector('.image-2-panel').classList.toggle('.active');
document.querySelector('.image-2-panel').classList.toggle('.notactive');
}
But nothing happens... I also have a for loop for sounds that is working still good, but the panels don´t move. Can someone share some light here? I thought in a loop and try it following the function but also didn´t work so clearly I am missing something, maybe wrong element I am trying to catch?
Above i have my question without the edit where you can understand what i mean.
Thanks for your help
I have 4 panels. In each panel, there will be 3 images/text one beyond the other. So it will work that when I press panel 1, panel 2,3 and 4 will turn to show an image. Press panel 2, and panel 1,3 and 4 will turn to show different image then when pressed the panel one. And so one for the rest of the panels.
So i start and i create a function for the first panel. It works, but there is any way i can make it simple? Here is the code:
function guessWho(){
document.querySelector('.image-1-panel').classList.toggle('notactive');
document.querySelector('.image-1-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('notactive');
document.querySelector('.image-3-panel').classList.toggle('active');
document.querySelector('.image-3-panel').classList.toggle('notactive');
document.querySelector('.image-4-panel').classList.toggle('active');
document.querySelector('.image-4-panel').classList.toggle('notactive1');
document.querySelector('.image-5-panel').classList.toggle('active');
document.querySelector('.image-5-panel').classList.toggle('notactive');
document.querySelector('.image-6-panel').classList.toggle('active');
document.querySelector('.image-6-panel').classList.toggle('notactive2');
document.querySelector('.image-7-panel').classList.toggle('active');
document.querySelector('.image-7-panel').classList.toggle('notactive');
document.querySelector('.image-8-panel').classList.toggle('active');
document.querySelector('.image-8-panel').classList.toggle('notactive3');
}
Any way I can put this simple? I don´t want to use any framework, so it has to be pure js. Thank you
Use a loop.
for (var i = 0; i <= 8; i++) {
document.querySelector(`.image-${i}-panel`).classList.toggle('notactive');
document.querySelector(`.image-${i}-panel`).classList.toggle('active');
}
Given that querySelector takes a string, you could build that string up inside of a loop and use the iterator inside of the string. Something like
for(i = 1; i <= 8; i++) {
document.querySelector('.image-' + i + '-panel').classList.toggle('notactive');
}
would toggle the 'notactive' class for everything that has image-x-panel.
Solution 1
for (var i = 1; i <= 8; i++) {
document.querySelector(`.image-${i}-panel`).classList.toggle('notactive');
document.querySelector(`.image-${i}-panel`).classList.toggle('active');
}
Solution 2
Add some CSS class to your HTML like CLASSNAME
And use try this
document.querySelector(`CLASSNAME`).classList.toggle('notactive');
document.querySelector(`CLASSNAME`).classList.toggle('active');
You can create a list of the new states you want your classes to be modified by. In this case, you have an object that looks like this:
{a:false,i:""}
where a is whether it's active, and i is your post class increment, like "notactive2".
Then you create a nested loop where you iterate over each number twice, and check the position in your list of states to determine what things will be added to your base "active" class.
var activeClassesList = [{a:false,i:""},{a:true,i:""},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"1"},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"2"},{a:true,i:""},{a:false,i:""},{a:true,i:""},{a:false,i:"3"}];
var imageClassPrefix = ".image-";
var imageClassPostfix = "-panel";
var start =1;
var base = 8;
for (var i=0;i<2;i++)
{
var count = 1;
for (var j=start;j<(start+base);j++) {
var modifier = activeClassesList[j-1];
var cls = (modifier.a ? "" : "not") + "active" + modifier.i;
document.querySelector(imageClassPrefix + String(count) + imageClassPostfix).classList.toggle(cls);
count++;
}
start = start + base;
}
Another approach might be to just focus on the results, so we can remove the first selectors for each image panel since they are immediately being overwritten.
That leaves the second queries for each selector. This can be simplified by combining multiple selectors inside a queryselectorAll for items with the same class being toggled.
function guessWho(){
document.querySelector('.image-1-panel').classList.toggle('active');
document.querySelector('.image-2-panel').classList.toggle('notactive');
document.querySelectorAll('.image-3-panel, .image-5-panel, .image-7-panel, .image-7-panel').forEach((f)=>{f.classList.toggle('notactive');})
document.querySelector('.image-4-panel').classList.toggle('notactive1');
document.querySelector('.image-6-panel').classList.toggle('notactive2');
}
guessWho();
.allpanels > div {display: inline-block;border:solid 1px black;height:50px;width:50px;margin:8px;}
.active { background-color:red;}
.notactive { background-color:lightsteelblue;}
.notactive1 { background-color:green;}
.notactive2 { background-color:orange;}
<div class="allpanels">
<div class="image-1-panel">1</div>
<div class="image-2-panel">2</div>
<div class="image-3-panel">3</div>
<div class="image-4-panel">4</div>
<div class="image-5-panel">5</div>
<div class="image-6-panel">6</div>
<div class="image-7-panel">7</div>
</div>

Append two different types of div's to a single container

I have two different div with classes called "red" and "blue". By default these are hidden. I want to clone and display them into a single container called "cont". Red button appends red div's blue button appends blue div's.
function redCreator(word){
var red =document.getElementsByClassName('red')[redPos];
redPos++;
var redClone = red.cloneNode(true);
document.getElementById('cont').appendChild(redClone);
item.style.display = 'inline';
item.innerHTML=word;
}
function blueCreator(word){
//same as red
}
Right now the red divs appear separately from blue div. Ignoring the time and order I clicked them
red1|red2|red3|blue1|blue2
How do I allow the divs to display in the order I clicked them? Regardless of the class.
red1|blue1|red2|blue2|blue3
One solution I came up with was to use a common class name and add the red/blue class later.
function redCreator(word){
var item =document.getElementsByClassName('input-item')[itemPos];
itemPos++;
var itemClone = item.cloneNode(true);
itemClone.className += " red";
document.getElementById('cont').appendChild(itemClone);
item.style.display = 'inline';
item.innerHTML=word;
}
However this doesn't work as expected. CSS is messed up
In Case you are looking for a pure JS solution :
HTML :
<div class="red input">red</div>
<div class="blue input">blue</div>
<div id="cont">
</div>
<button onclick="redCreator('red');">RED</button>
<button onclick="blueCreator('blue');">blue</button>
CSS
.input {
display: none;
padding:10px;
}
.red {
background:red;
}
.blue {
background:blue;
}
JS:
function redCreator(word){
var red =document.getElementsByClassName('red')[0];
console.log(red);
var redClone = red.cloneNode(true);
document.getElementById('cont').appendChild(redClone);
redClone.style.display = 'inline-block';
redClone.innerHTML=word;
}
function blueCreator(word){
var blue =document.getElementsByClassName('blue')[0];
var blueClone = blue.cloneNode(true);
document.getElementById('cont').appendChild(blueClone);
blueClone.style.display = 'inline-block';
blueClone.innerHTML=word;
}
Just add some lines to get the numbering and you will be fine.
Happy coding.
So using jQuery (the fiddle is using 1.9.1 - but it should be forward compatible) I have put together a fiddle:
https://jsfiddle.net/27oa1pb7/
In this - it takes contents of hidden divs and appending them in the order you click them into the "cont" container ... using CSS, you could change the display of the divs, etc. It uses a very basic chain of jQuery commands:
...
$("#reddiv").clone().show().appendTo( "#cont" )
...
This code is what I came up with using your description, as there is no HTML or CSS example stating exactly what you may need.
Hope this helps!
Happy coding!

dynamically insert div after row containing floating divs jquery [duplicate]

I have a number of divs floating in several rows. The divs contain text-previews and a link to slide down the full content (see http://jsfiddle.net/yDcKu/ for an example).
What happens now: When you slide down the content-div it opens right after the connected preview.
What I want to happen: Open the content-div after the last div in the row.
I assume the could be done by:
1. find out which div is the last one in the row of the activated preview,
2. add an id to this div and
3. append the content-div to this div.
I have a solution for steps 2 und 3 using jQuery but no guess how to do the first step.
I can manage to get the document width and the x- and y-value of each div but I have no idea how to find out which div has the highest x- as well the highest y-value and as well is in the row of the activated preview-div.
Any idea anyone? Thanks
Here is an example that does what you want. I simplified your code, so you don't have to manually ID every entry and preview.
http://jsfiddle.net/jqmPc/1/
It's a little complicated. Let me know if you have questions.
Basically, when the window is resized, the script goes through and finds the first preview in each row by finding the preview with the same left offset as the very first one. It then adds a class last to the entry before (previous row) and class first to this preview. I do css clear: left on both of these so that everything wraps normally when the entries open.
I made your code generic, without IDs:
<div class="preview">
<p>Some preview text <a class="trigger" href="#">…</a></p>
</div>
<div class="entry">
<div class="close_button">
<a class="close" href="#">×</a>
</div>
<p>Some content text.</p>
</div>
This makes you not have to write the same code over and over.
The open/close script:
$('.trigger').click(function() {
$('.openEntry').slideUp(800); // Close the open entry
var preview = $(this).closest('.preview'); // Grab the parent of the link
// Now, clone the entry and stick it after the "last" item on this row:
preview.next('.entry').clone().addClass('openEntry').insertAfter(preview.nextAll('.last:first')).slideDown(800);
});
// Use "on()" here, because the "openEntry" is dynamically added
// (and it's good practice anyway)
$('body').on('click', '.close', function() {
// Close and remove the cloned entry
$('.openEntry').slideUp(800).remove();
});
This could be simplified a bit I'm sure, especially if you were willing to reformat your html a little more, by putting the entry inside of the preview element (but still hidden). Here is a slightly simpler version, with the html rearranged:
http://jsfiddle.net/jqmPc/2/
(I also color the first and last element on the line so you can see what is going on)
You could just get the last div in the array after calling getElementsByTagName.
var divArray = wrapperDiv.getElementsByTagName("div");
if(divArray.length > 0)
var lastDiv = divArray[divArray.length-1];
else
console.log("Empty!");
i am not able to correctly understand your question, but if you want to find out last div element in the document then you can do something like this
$("div:last")
so this will give you last div of the document
Reference:
http://api.jquery.com/last-selector/
$([1,2]).each(function(idx,el) {
$("#entry" + el).hide().insertAfter("div.entry:last");
$("#trigger" + el).click(function() {
$("#entry" + el).slideDown('800');
});
$("#close" + el).click(function() {
$("#entry" + el).slideUp('800');
});
});​
http://jsfiddle.net/yDcKu/11/
I got same problem as yours, and I have been redirected to this question. But I think the answer is too complicated to my need. So I made my own way. Supposedly, you get your div list from a JSON, you can do this:
product[0] = {id: "name1", text: "text1"}
product[1] = {id: "name2", text: "text2"}
product[2] = {id: "name3", text: "text3"}
private getLastElement(id, products) {
const getTop = (id) => $("#" + id).position().top;
let itemPos = getTop(id);
let itemIndex = products.map(x => x.id).indexOf(id);
let lastID = itemIndex;
while (lastID < products.length - 1) {
if (getTop(products[lastID + 1].id) > itemPos) break;
lastID++;
}
return products[lastID].id;
}
But you can also find out by gathering all id inside your wrapper.
It works by scanning next id's row position, and return the last id of the same row.
I was looking for the same but on a single element to add style on first and last elements. #Jeff B answer helped me so alter and use it for me on one element. So the search phrase 'Get the last div in a row of floating divs' and someone looking for the same, this code may helpful:
Fiddle: https://jsfiddle.net/kunjsharma/qze8n97x/2/
JS:
$(function() {
$(window).on('resize', function() {
var startPosX = $('.preview:first').position().left;
$('.preview').removeClass("first last");
$('.preview').each(function() {
if ($(this).position().left == startPosX) {
$(this).addClass("first");
$(this).prevAll('.preview:first').addClass("last");
}
});
$('.preview:last').addClass("last");
});
$(window).trigger('resize');
});
CSS:
.preview {
float: left;
}
HTML:
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>
<div class="preview">
<p>Some preview text</p>
</div>

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

4 toggle buttons speak javascript to each other but none of them are good listeners

update at the bottom
There are 4 divs that are set to look like toggle buttons. When a button is toggled on:
-it is animated as a pressed button,
-it retrieves some content and it places that content into a box, and then
-it returns a value of 1 to an array.
(no problem.)
Problem:
When there is already one button button pressed, I don't understand how to toggle the first button off without also turning the other one off or affecting the other buttons. How can I pass the output of one button to the others so they know who they have to turn off when they turn on?
My solution thus far has been to create 2 arrays:
var arrayValues [ a, b, c, d]; //the values of each button state: [0,0,0,0] <-all off | all on-> [1,1,1,1]
var addedValues = [a + b + c + d]; //the values of each array item added together: [0+0+0+0]= 0 <-all off | all on-> [1,1,1,1]=4
and then
if (addedValues = 0) {
console.log("cool, nothing is pressed yet. I am going to return true, but where does that return value go? How can I access it?");
return true;
} else if (addedValues > 1) {
console.log("ok I now know that at least one button has already been pressed, but how can I tell the other buttons which one was already pressed?");
}
For example if the first button is toggled on
arrayValues = [1,0,0,0]
and now the second button has been toggled on so it says
arrayValues = [1,1,0,0]
but how can I pass that information into all of the buttons? This next part is obviously flawed but it's the only thing I could think of doing:
} else if(addedValues >= 2) {
arrayValues[0] = arrayValues[0] - 1;
arrayValues[1] = arrayValues[1] - 1;
arrayValues[2] = arrayValues[2] - 1;
arrayValues[3] = arrayValues[3] - 1;
}
so now, the only values that are not negative are the two buttons in active states... but that does nothing for because we already knew that. How can I tell the buttons which button to subtract 1 from without affecting any of the other buttons?
Update: To see the madness in context http://jsfiddle.net/Luhring/EjW7A/23/
*update: *
Just to clarify: the buttons aren't only just toggling their appearances, they're changing other content displayed on the page:
When you click each button the content changes. each button has 1 original group of original content that is toggled on/off with the button. like changing the channel on a tv screen with a remote control.
so if button 1 is pressed, when button 2 is pressed button 1 must turn off (removing its' content and animating back up to its' original position) in order to allow button 2's stuff to display.
shout out to #nbrooks for writing 4 lines of code that more or less did as much as I did in +100. Still not solved but his is WAY more efficient than mine (you can see his version here: http://jsfiddle.net/EjW7A/20/ ) )
Updated Demo, according to new reqs: http://jsfiddle.net/EjW7A/24/
$(function() {
$('.plain').click(function() {
var newClassName = $(this).is('.selected') ? '' : this.id;
if ($(this).is('#content')) return;
$(this).toggleClass('selected', 1000);
$('#content').attr('class', 'plain '+newClassName);
$('.selected').not(this).removeClass('selected');
});
});​
Update to your fiddle demo
The best way to do this is just give the elements a common class, to which you can bind a click handler and a css rule. This will accomplish your function of only having one button being pressed at a time, plus the ability to turn it on/off without affecting the others.
Javascript (jQuery):
$(function() {
$('.plain').click(function() {
$(this).toggleClass('selected');
$('.selected').not(this).removeClass('selected');
});
});​
HTML
<div id="a" class="plain">
<p>A</p>
</div>
CSS
.plain {
width: 200px; height: 200px; margin: 20px; text-align:center; float: left;
font-size: 100px; color:#fff; background-color:red;
}
p { margin-top: 25%; margin-bottom:25%; }
.selected { background-color: blue; }
If you are doing the submitting with JavaScript, then this should be a much simpler approach: http://jsfiddle.net/EjW7A/15/
HTML
<div id="a" class="a1 toggleButton">
<p>A</p>
</div>
<div id="b" class="b1 toggleButton">
<p>B</p>
</div>
<button id ="test">test</button>​
JavaScript
jQuery(function() {
jQuery(".toggleButton").click(function() {
jQuery(".toggleButtonToggled").removeClass("toggleButtonToggled");
jQuery(this).addClass("toggleButtonToggled");
});
jQuery("#test").click(function() {
var value = jQuery(".toggleButtonToggled:first").attr('id');
alert("Toggled button is: "+ value);
});
});​

Categories

Resources