Contenteditable add/remove class if child id :focus - javascript

I have a div set as contenteditable and everything inside of that div can be edited. Now when I click on the div I automatically add a class selected (If visible prior I remove it and add it to the new selection) I have next and forward buttons so I can change my selection if I'm on using a tablet or smart phone.
Now here's where I need help.
So I selected the middle div and as I move my cursor to another child of #dynamic-storage I'm left with the problem of removing the class selected and adding it to the new child that's selected. (Not the span in the example as it's parent is a div. That's what I want selected as the div's in this example are the children of #dynamic-storage (ex. #dynamic-storage > div)
The snippet provided at the bottom of this post does not contain the arrows or menubar provided in the screenshot and fiddle links above as that code is not necessary at the given time of posting. I'm keeping this post focused on the one task being handling the .selected class for the focused child of #dynamic-storage.
$(document).ready(function() {
// Select Elements
var SelectElements = function() {
$("#dynamic-storage").children().on("mouseup touchend", function() {
if ( $(".selected").is(":visible") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
};
// Clear Selection
var ClearSelection = function() {
$(".selected").removeClass("selected");
};
SelectElements();
// Handles Hotkeys
$(document).keyup(function(e) {
// Up & Down Arrow Keys To Select/Deselect Element in Editable
if (e.which === 38 || 40 ) {
if ( $(".selected").is(":focus") ) {
alert("correct");
} else if ( $(".selected").is(":blur") ) {
alert("incorrect");
}
}
});
});
/* Body */
#dynamic-storage {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 0;
outline: 0;
}
#dynamic-storage .selected {
outline: 2px dotted #69f;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<link type='text/css' rel='stylesheet' href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="dynamic-storage" contenteditable="true">
<div class="header" align="center">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
<span>Hello world</span>
</div>
<div class="header selected" align="left">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
</div>
<div class="header" align="right">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
</div>
</div>
</body>
</html>
Fiddle: http://liveweave.com/uyz4VK
Fiddle: http://jsbin.com/kujuxofeju/1/edit?html,js,output

Element with attribute contenteditable='true' has all its content editable as in a single textarea. That is the reason why focus/blur event will not happen when you move cursor. Everywhere inside element with contenteditable='true' you are still in the same textarea not leaving or entering it.
The solution here is to deal with coursor positioning similar to textarea.
To get an object that represents current selection we use function:
var getSelection;
if (window.getSelection) {
// IE 9 and non-IE
getSelection = function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
} else if (document.selection && document.selection.createRange) {
// IE <= 8
getSelection = function() {
var sel = document.selection;
return (sel.type != "None") ? sel.createRange() : null;
};
}
Then we need to do the next operations: remove class .selected from the first level children of #dynamic-storage, get element with cursor, and go up the DOM to find its parent closest to #dynamic-storage to add class .selected:
// Handles Hotkeys
$(document).keyup(function(e) {
// Up & Down Arrow Keys To Select/Deselect Element in Editable
if (e.which === 38 || 40 ) {
$('#dynamic-storage > div').removeClass('selected');
var selectedElem = getSelection()[0].commonAncestorContainer.parentElement;
$(selectedElem).closest('#dynamic-storage > div').addClass('selected');
}
});
Here is the working fiddle

Something along the lines of (try this in your main jQuery function) :
$("#dynamic-storage").children().each(function() {
$(this).on("focus", function() {
$(this).addClass("selected");
});
$(this).on("blur", function() {
$(this).removeClass("selected");
});
});
But if you edit the contents, you will loose the event handlers bound to them ...

Related

How to hide current content by clicking outside its area, and when I show another content in IE11?

Clicking on the button shows and hides the corresponding content.
function funC(id) {
var el = document.getElementById(id);
if(el.style.display == 'inline-block')
el.style.display = '';
else
el.style.display = 'inline-block';
}
button {margin:2px; outline:0; font-size:12px;}
span {padding:2px; border:1px solid silver;
font-size:12px;}
.cb {display:none;}
<button onclick="funC('cnt1');">b1</button><span id="cnt1" class="cb">content b1...</span>
<br />
<button onclick="funC('cnt2');">b2</button><span id="cnt2" class="cb">content b2...</span>
<br />
<button onclick="funC('cnt3');">b3</button><span id="cnt3" class="cb">content b3...</span>
fiddle example
1. But, how to hide content when clicking outside its area,
and as with showing the next content, hide the previous one?
2. Is it possible to do the same without using id?
Only pure javascript. Thank you.
This might not be a perfect solution but here is a proposition :
function hideAllContent() {
var elements = document.querySelectorAll(".cb");
for(var i =0, l = elements.length; i < l; i++) {
var element = elements[i];
element.visible = false;
element.style.display='none';
}
}
function funC(id, event) {
// We need to stop the event to avoid bubling until the body
event.stopPropagation();
// let's hide others before displaying the new one
hideAllContent();
var el = document.getElementById(id);
if(el.visible) {
el.visible = false;
el.style.display = 'none';
} else {
el.visible = true;
el.style.display = 'inline-block';
}
}
document.body.onclick = function(event) {
if (!event.target.classList.contains('cb')) {
hideAllContent();
}
}
button {margin:2px; outline:0; font-size:12px;}
span {padding:2px; border:1px solid silver;
font-size:12px;}
.cb {display:none;}
<button onclick="funC('cnt1', event);">b1</button><span id="cnt1" class="cb">content b1...</span>
<br />
<button onclick="funC('cnt2', event);">b2</button><span id="cnt2" class="cb">content b2...</span>
<br />
<button onclick="funC('cnt3', event);">b3</button><span id="cnt3" class="cb">content b3...</span>
About avoiding ids, you could use the target property on click event and find the sibling node or something like that or use a querySelector. But ids are safe and fine i would say.
No inline on-clicks attached.
No IDs use.
Used backward-compatible syntax for IE 11.
// JavaScript
// get all button and span tags
var btns = document.querySelectorAll('button');
var otherSpans = document.querySelectorAll('span');
// Detect all clicks on the document
document.addEventListener("click", function(event) {
const spanElems = document.querySelectorAll('span');
const spanElemsArray = Array.prototype.slice.call(spanElems);
let matches = event.target.matches ? event.target.matches('button') : event.target.msMatchesSelector('button');
// If user clicks inside the element, do nothing
if (matches) {
return;
} else {
// If user clicks outside the element, hide it!
spanElemsArray.forEach( function (spanElem) {
spanElem.classList.remove("open");
});
}
});
// convert buttons and spans variable objects to arrays
const btnsArray = Array.prototype.slice.call(btns);
const otherSpansArray = Array.prototype.slice.call(otherSpans);
// loop through every button and assign a click to each one
btnsArray.forEach( function (btn) {
btn.addEventListener('click', spanFunc)
});
// Pass the button clicked as a reference
function spanFunc(){
openSpan(this);
}
// toggle the display class on the span next to the button using nextElementSibling method
function openSpan(e) {
e.nextElementSibling.classList.toggle("open");
// hide every other spans
function otherSpanFunc() {
otherSpansArray.forEach( function (otherSpan) {
if (otherSpan !== e.nextElementSibling) {
otherSpan.classList.remove('open');
}
});
}
otherSpanFunc();
}
/* css */
button {margin:2px; outline:0; font-size:12px;}
span {padding:2px; border:1px solid silver;
font-size:12px;}
.cb {display:none;}
.open {display:inline-block;}
<!-- HTML -->
<button>b1</button><span class="cb">content b1...</span>
<br />
<button>b2</button><span class="cb">content b2...</span>
<br />
<button>b3</button><span class="cb">content b3...</span>
jsFiddle: https://jsfiddle.net/ypofz4d5/55/

Javascript - Deleting a list item

How do you properly delete list item by clicking on it?
I have been using the following line for code to delete an item but instead this deletes the entire list itself:
var list = document.getElementById("shoppinglist");
list.onclick = function() { list.parentNode.removeChild(list);}
I have been searching online on how to do this and the same kind of code keeps appearing and I am not sure how to solve this. I assumed that the list item generated was a child of the "shoppinglist".
I am very new to Javascript and I know this is a rookie mistake but I would really appreciate any help. Thank you.
<!doctype html>
<html dir="ltr" lang="en-gb">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style>
body {
/* Sets the width then uses the margin auto feature to centre the page in the browser */
width:800px;
margin: 0px auto; /*0px top/bottom auto left/right */
font-size:10px; /* By default fonts are usually 16px but may not be in some browsers */
}
p, li {
font-size:1.5em; /* Set all text to be 1.5 * overall font size = 15 pixels */
}
section {
/* each of the two sections will use just under half the width of the width of the body */
width:395px;
display:block;
}
#choices {
/* float the choices list to the left of the page */
float:left;
background-color: #FFFF99;
}
#cart {
/* float the shopping cart to the right of the page */
float:right;
background-color: #7FFF00;
}
.cartlist {
/* Simplify the display of the lists, removing default bullet points and indentation */
list-style-type:none;
margin:0px;
padding:0px;
width:inherit;
}
.cartlist li {
/* Set each list item to be 2* the height of the text */
height:2em;
}
.cartlist li:nth-child(odd) {
/* Colour odd list items ie first, third, fifth etc, a different colour */
background-color:#eee;
}
#outputinfo {
/* prevents the DIV from joining the floating behaviour so it displays below the lists */
clear:both;
}
</style>
</head>
<body>
<section id="choices">
<p>Available Choices</p>
<ul id="sourcelist" class="cartlist">
<li data-value="2.99">£2.99 : Chocolate</li>
<li data-value="3.49">£3.49 : Cereal</li>
<li data-value="0.98">£0.98 : Milk</li>
<li data-value="0.89">£0.89 : Bread</li>
<li data-value="3.79">£3.79 : Coffee</li>
<li data-value="2.53">£2.53 : Strawberries</li>
<li data-value="3.89">£3.89 : Cheesecake</li>
</ul>
</section>
<section id="cart">
<p>Shopping Cart</p>
<ul id="shoppinglist" class="cartlist"></ul>
</section>
<div id="outputinfo">
<p><button id="calctotal">Calculate Total</button> : <span id="totalresult"></span></p>
</div>
</body>
<script>
function getTargetElement(e) {
var targetelement=null;
targetelement=(e.srcElement || e.target || e.toElement)
return targetelement;
}
function calcTotal() {
var shoppinglist=document.getElementById("shoppinglist");
var total=0;
for(i=0;i<shoppinglist.children.length;i++) {
total+=parseFloat(shoppinglist.children[i].getAttribute("data-value"));
}
var totalresult=document.getElementById("totalresult");
totalresult.innerHTML="£"+total.toFixed(2);
}
function handleEvent(e) {
var listclicked=getTargetElement(e);
var newlistitem=document.createElement("li");
var datavalue=listclicked.getAttribute("data-value");
newlistitem.setAttribute("data-value",datavalue);
newlisttext=document.createTextNode(listclicked.innerHTML)
newlistitem.appendChild(newlisttext);
var shoppinglist = document.getElementById("shoppinglist");
shoppinglist.appendChild(newlistitem);
var list = document.getElementById("shoppinglist");
list.onclick = function() { list.parentNode.removeChild(list);}
console.log(listclicked);
}
function removeItem(e){
var listclicked=getTargetElement(e);
var node = document.getElementById('shoppinglist');
listclicked.parentNode.removeChild(listclicked);
}
document.onreadystatechange = function(){
if(document.readyState=="complete") {
var sourcelist=document.getElementById("sourcelist");
for(i=0;i<sourcelist.children.length;i++) {
if(document.addEventListener) {
sourcelist.children[i].addEventListener("click", handleEvent, false);
} else {
sourcelist.children[i].attachEvent("onclick", handleEvent);
}
var totalbutton=document.getElementById("calctotal");
if(document.addEventListener) {
totalbutton.addEventListener("click",calcTotal,false);
} else {
totalbutton.attachEvent("onclick",calcTotal);
}
}
}
}
</script>
</html>
You don't want to remove the entire list, just the clicked LI element.
As you don't seem to have nested elements, event delegation becomes a little easier
var list = document.getElementById("shoppinglist");
list.addEventListener('click', function(evt) {
list.removeChild(evt.target);
},false);
FIDDLE
For the future, if you wanted nesten elements, you could use element.closest()
var list = document.getElementById("shoppinglist");
list.addEventListener('click', function(evt) {
var p = evt.target.closest('li');
list.removeChild(p);
}, false);
Note the somewhat lacking support in older browsers for closest(), but there are several polyfills available if needed.
Also note that you're binding event handlers inside event handlers, which is a big no-no, your code does the equivalent of
var sourcelist = document.getElementById("sourcelist");
for(i = 0; i < sourcelist.children.length; i++) {
sourcelist.children[i].addEventListener("click", handleEvent, false);
...
// and then
function handleEvent(e) {
var list = document.getElementById("shoppinglist");
list.addEventListener('click', function(evt) {
list.removeChild(evt.target);
},false);
....
so every time you add another list item to the list, you bind a new event handler, and it adds up, but you only need one single event handler, having multiple event handlers will just try to remove the same element over and over again, but it's removed the first time.
list.onclick = function() { list.parentNode.removeChild(list);}
list is the whole list (<ul id='list'>). You're listening for a click on the whole list. Then grabbing the whole list's parent node with list.parentNode ( which gives you <section id="cart">) and deleting the list from it.
Your code is doing exactly what you told it to do.
Like this:
list.removeChild(list.childNodes[indexToRemove])
You need to specify what node to remove. You can test this in chrome by opening up the console and pasting the following:
var list = document.getElementById("shoppinglist");
console.log('List:', list)
console.log('List children:', list.childNodes)
var indexToRemove = 0;
list.removeChild(list.childNodes[indexToRemove]);
console.log('List:', list)
console.log('List children:', list.childNodes)
You can use this:
var list = document.getElementById("shoppinglist");
list.onclick = function(e) { e.target.parentNode.removeChild(e.target);}
You can read more about target and currentTarget and checkout this example http://fiddle.jshell.net/hidoos/Lpz917vo/

assign selected text to a variable in designMode

I have a piece of code that sets the document to designMode and then operates on pieces of selected text using the document.execCommand() function.
It provides various functionality - for example it allows the user to turn a selected line of text to bold or italic (essentially the functionality of a text editor like this one that I am typing into now).
Here is a simplified example of the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
This is some text - highlight a section of it and press h1 then li
</div>
<button onclick="setToHeader()" id="h1" style="width:100px" unselectable="on">h1</button>
<button onclick="setToList()" id="li" style="width:100px" unselectable="on">li</button>
<script>
document.designMode = 'on';
function setToHeader() {
document.execCommand('formatBlock', false, 'h1');
}
function setToList() {
document.execCommand('insertUnorderedList', false, null);
}
</script>
</body>
</html>
My problem here is that I do not want to be able to use the li button - i.e. convert the selected text to list format, when it is already converted into heading format with the h1 button.
I think I want to be able to read the selected text and simply check it with something like:
// var selectedText = ???
var isHeading = selectedText.search('h1') > -1
Is this the way, or is there a better approach?
How can I get hold of the relevant selected text and assign it to a variable?
You need a little bit more effort. Need to use jquery also, check it out:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>This is some text - highlight a section of it and press h1 then li </div>
<div>This is some other text - highlight a section of it and press h1 then li </div>
<button onclick="setToHeader()" id="h1" style="width:100px" unselectable="on">h1</button>
<button onclick="setToList()" id="li" style="width:100px" unselectable="on">li</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
document.designMode = 'on';
setInterval(function () {
var el = getSelectionContainerElement();
if($(el).is('h1')){
$("#li").attr("disabled", true);
}
else
{
$("#li").attr("disabled", false);
}
}, 100);
function setToHeader() {
document.execCommand('formatBlock', false, 'h1');
}
function setToList() {
document.execCommand('insertUnorderedList', false, null);
}
function getSelectionContainerElement() {
var range, sel, container;
if (document.selection && document.selection.createRange) {
// IE case
range = document.selection.createRange();
return range.parentElement();
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
} else {
// Old WebKit selection object has no getRangeAt, so
// create a range from other selection properties
range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
if (range) {
container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
return container.nodeType === 3 ? container.parentNode : container;
}
}
}
</script>
</body>
</html>
You can get hold of the selected text using the selection object.
e.g. in IE11:
getSelection()
Full documentation can be found here:
https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx

How to leave one active button in the JavaScript?

I am beginner.
I have four buttons and I want to leave one active button every time with expression operator (if). One button must have active every time .
I tried to do it something like that. I am open to your ideas, if you can do without (if) .Help me!
var count = 4;
var flag = true;
function select(currentColor, changeColor){
if(count > 1 && flag === true){
var currentElement = angular.element(document.getElementsByClassName(currentColor));
currentElement.toggleClass(changeColor);
count--;
console.log(count);
console.log('From minus: ' + count);
}else{
flag = false;
}
if(count < 4 && flag === false) {
var currentElement = angular.element(document.getElementsByClassName(currentColor));
currentElement.toggleClass(changeColor);
count++;
console.log(count);
console.log('From plus: ' + count);
}else{
flag = true;
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<style>
.changeColor{
color: red !important;
}
.first{
color: #07888A;
}
.second{
color: #07888A;
}
.third{
color: #07888A;
}
.fourth{
color: #07888A;
}
h1{
display: inline;
margin-right: 20px;
}
</style>
</head>
<body>
<h1 class="first" onClick="select('first', 'changeColor')">First</h1>
<h1 class="second" onClick="select('second', 'changeColor')">Second</h1>
<h1 class="third" onClick="select('third', 'changeColor')">Third</h1>
<h1 class="fourth" onClick="select('fourth', 'changeColor')">Fourth</h1>
</body>
</html>
Add this bit:
function select(currentColor, changeColor) {
// Get the list of the `.changeColor` elements.
changed = document.querySelectorAll(".changeColor");
// Loop through all the elements with `changeColor` class.
for (i = 0; i < changed.length; i++)
// Remove the changeColor class from their class list.
changed[i].classList.remove("changeColor");
// Rest comes your code.
if(count > 1 && flag === true){
are you trying to get one button disabled when any three buttons are enabled ? if so, perhaps this could help. I highly suggest not to use the h1 tags for this purpose, and use something like a button or div, and removing the onclick attributes from your elements and incorporate them in your main js file similar to the js snippet found below.
(function() {
//an empty array to track the number of elements currently colored
var numberOfElesColored = [],
eles = document.querySelectorAll('h1'),
//the number of active elements allowed at once
numberOfActiveElementsAllowed = eles.length - 1;
//loop though all the elements and attach click event
[].forEach.call(eles, function(ele, i) {
ele.addEventListener('click', function(event) {
var currentEle = event.target;
//is there at least two other elements avaliable still ?
if (!(numberOfElesColored.length === numberOfActiveElementsAllowed)) {
//yes
//is the current clicked element not active already ?
if (!currentEle.classList.contains('changeColor')) {
//yes
//add 1 to tracking array
numberOfElesColored.push(1);
//activate element
return currentEle.classList.add('changeColor');
} else {
//no
//remove 1 from tracking array
numberOfElesColored.pop();
//deactivate elements
return currentEle.classList.remove('changeColor');
}
//are all the elements active already ?
} else if (numberOfElesColored.length === numberOfActiveElementsAllowed) {
//yes
//is the current element an active one ?
if (currentEle.classList.contains('changeColor')) {
//yes
//remove 1 from tracking array
numberOfElesColored.pop();
//deactivate element
return currentEle.classList.remove('changeColor');
}
}
});
});
})();

How to iterate through jquery selection

I am trying to figure out how jquery selectors work when selecting a group of elements. Once i have the all of the elements i am trying to iterate through and check a style value of them to find which one has that and it does not seem to work. Do i have to iterate through them differently? Thank you for any help. I have tried searching and messing with it and this is what i have as of now.
function toggle() {
//get all the content divs
var $all_divs = $('.content_div');
//find the content div that is visable
var $active_index = -1;
for (i = 0; i < $all_divs.length(); i++) {
if ($all_divs[i].style.display == "block") {
$active_index = i;
}
}
$all_divs[$active_index].style.display = "none";
}
edit:
Some more info on where i am headed with this.
Basically i have 4 divs, and when i click a button i want the one that is visible to go away, and the next one in the list to appear.
Whole code:
<!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 type="text/css">
.wrapper {
width:450px;
height:30px;
position:relative;
}
.slide_button {
width:25px;
height:30px;
position:absolute;
top:0;
}
#left {
left:0;
}
#right {
left:425px;
}
.content_div {
width:400px;
height:30px;
position:absolute;
top:0;
left:25px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
function toggle() {
var Divs = $('.content_div');
var i;
var index = 0;
Divs.each(function(index) {
if ($(this).css('display') == 'block')
i = index;
index++;
});
if(typeof i !== 'undefined'){
Divs.eq(i).css('display', 'none');
}
}
</script>
</head>
<body>
<div class="wrapper">
<div class="slide_button" id="left">
<center><a href='javascript:toggle();'><</a></center>
</div>
<div id='div1' class='content_div' style="display:block;">
this is div 1
</div>
<div id='div2' class='content_div' style="display:none;">
this is div 2
</div>
<div id='div3' class='content_div' style="display:none;">
this is div 3
</div>
<div class="slide_button" id='right'>
<center>></center>
</div>
</div>
</body>
</html>
I think the reason your code doesn't work is the use of .length() in the for loop condition. jQuery objects don't have a .length() method, they have a .length property. Drop the brackets and your code should work.
EDIT: For your requirement to display the divs one at a time you can do something like this:
$(document).ready(function() {
var $divs = $("div.content_div").hide(), // first hide all the divs
i = 0;
$divs.eq(i).show(); // then show the first
$(".slide_button a").click(function() {
$divs.eq(i).hide(); // on click hide the current div
i = (i+1) % $divs.length; // then update the index to
$divs.eq(i).show(); // show the next one
});
});
Demo: http://jsfiddle.net/7CcMh/
(The rest of my original answer:)
The syntax you are using to access the individual elements is OK: if $all_divs is a jQuery object, which it is, then $all_divs[0] is a reference to the first DOM element in the jQuery object. However, jQuery provides the .each() method to make this process easier:
$('.content_div').each(function() {
// here 'this' is the current DOM element, so:
if (this.style.display == "block")
this.style.display = "none";
// OR, to access the current element through jQuery methods:
$(this).css("display", "none");
});
Having said that, it seems you expect all but one element to be hidden already and you are finding that one and hiding it too. If so, you can achieve that in one line:
$('.content_div').hide();
// OR
$('.content_div').css("display", "none");
jQuery methods like .hide() and .css() apply to all elements in the jQuery object they're called on.
You can use jQuery each() method which lets you iterate through the selected elements.
$('.content_div').each(functon(index){
if ($(this).is(':visible')) {
$(this).hide()
}
})
If you want to select the visible divs you can use the :visible selector:
Selects all elements that are visible.
$('.content_div:visible').css('display', 'none'): // or $('.content_div:visible').hide()
update:
you can add a class to the anchor and try the following:
<center>></center>
$('.toggle').click(function(e){
e.preventDefault()
if ($('.content_div:visible').next('.content_div').length != 0) {
$('.content_div:visible').hide().next('.content_div:hidden:first').show()
} else {
$('.content_div').hide().eq(0).show()
}
})
Demo
Use the standard each method from JQuery.
$('.content_div').each(function(index) {
// do work with the given index
if (this.style.display == "block") {
this.style.display = "none";
}
});
Last changes:
http://jsfiddle.net/6fPLp/13/

Categories

Resources