Hiding div clicking on other [duplicate] - javascript

This question already has answers here:
How to display one div and hide all others
(7 answers)
Closed 10 years ago.
I have four button and four div above it.
I want to only one div at time , but keep showed the four button.
Here it is the html for buttons
HTML
<div id="container">
<a><p id="firstBtn" class="mediabutton"><span class="icon"></span>button1</p></a> <!-- 1st button -->
<div id="firstDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
<a><p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p></a> <!-- 2st button -->
<div id="sndDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
This is how I can recogniz which button was clicked
Javascript
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") )
&& !($("#"+that).hasClass("active"))
)
{
//Here comes the stuff
}
});
Now. The active class let the button to be Highlighted. I want only one button highlight.
The sndDiv is set on display : block , the others are set on display: none.
Making a recap : I want to press a button , show the div above it and hide everybody else. I tried really a lot of stuff, but i failed.
Sorry for my english, Cheers.

Just replace Btn with Div, and you have the element you'd like to show, the others have a common class and are easy to target :
$("#container").on('click', '.mediabutton', function(event){
var that = event.target.id,
elem = $('#' + that.replace('Btn','Div'));
if( !$("#"+that).hasClass("active") ) {
$('.mediaoptions').not(elem).hide();
elem.show()
}
});

The following should work.
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") ) && !($("#"+that).hasClass("active")))
{
$('.mediaoptions').show();
$('#'+that.replace('Btn','Div')).show();
}
});

I hate to just point you to a link, but I created a really lightweight jQuery script to handle stuff like this that you might found useful: http://cferdinandi.github.com/tabby/.
You may find it easier to just repurpose that than try to modify your existing code to work.

Don't jQuery .hide() and .show() do the job?
http://api.jquery.com/hide/

Add the second line below to your javascript and see what is alerted:
var that = event.target.id;
alert(that);
I'm not sure exactly what you're trying to accomplish perhaps something like:
<p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p>

See this example: JsFiddle. I made some updates on javascript and html;
$(".mediabutton").click(function(event){
$(".mediabutton").removeClass("active");
$(this).addClass("active");
$(".mediaoptions").hide();
$("#"+$(this).data("target-div")).show();
});

Here is the working jsFiddle: http://jsfiddle.net/CtqUU/
With this you can have as many <div> and <button> elements as you want. Change class names and id as needed to fit what you need.
HTML:
<div class="hidden" id="box1">Box 1</div>
<button value="box1">Box 1</button>
<div class="hidden" id="box2">Box 2</div>
<button value="box2">Box 2</button>
CSS:
div {
width: 200px;
height: 200px;
border: 1px solid #000000;
}
.hidden {
display: none;
visibility: hidden;
}
JS:
$("button").click(function(){
var val = $(this).val();
$("div").addClass("hidden");
$("#"+val).removeClass("hidden");
});

Related

DIV content hide/show based on URL

In html page am having an div-reportControlPanel as below . I have included another div-reportControlPanel1 as same with different id .
<div id="reportControlPanel" class="pentaho-rounded-panel-bottom-lr pentaho-shadow">
<div id="promptPanel" class="pentaho-rounded-panel-bottom-lr"></div>
</div>
<div id="reportControlPanel1" class="pentaho-rounded-panel-bottom-lr pentaho-shadow">
<div id="promptPanel" class="pentaho-rounded-panel-bottom-lr"></div>
</div>
Here Am show/hide the div's based on url am triggering .
if(prptName == "css.prpt")
{
alert("if");
document.getElementById("reportControlPanel").style.display = 'none';
document.getElementById("reportControlPanel1").style.display = 'block';
}
But as am using same sub Div-promptPanel under two different div my content is not loading properly . promptPanel is pentaho system used div. I am trying to have an another div to modify some css for my prpt.
Thanks.
To reiterate what Moishe said to you already: id are meant to be unique. You currently have two promptPanel id's, which means the second one will likely never be called. Now, you could use javascript, but with minimal knowledge of what your code looks like you could use a simple hash url + some basic css.
$(document).ready(function() {
$('a').click(function() {
$('#url').html($(this).prop('href'));
});
});
div.pentaho-rounded-panel-bottom-lr {
display: none;
}
div.pentaho-rounded-panel-bottom-lr .pentaho-rounded-panel-bottom-lr {
display: block;
}
:target {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="url"></div>
"Open" panel 1
"Open" panel 2
<div id="reportControlPanel1" class="pentaho-rounded-panel-bottom-lr pentaho-shadow">
<div id="promptPanel" class="pentaho-rounded-panel-bottom-lr">
this is some text in the first control panel.
</div>
</div>
<div id="reportControlPanel2" class="pentaho-rounded-panel-bottom-lr pentaho-shadow">
<div id="promptPanel" class="pentaho-rounded-panel-bottom-lr">
this is some text in the second control panel
</div>
</div>

displaying a group of divs by clicking next and back buttons

I have 5 divs that contain copy.
I have a back and next button, to display each div.
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
// hide the divs, except the first one.
.vote-result { display: none; }
.vote-result.first { display: block; }
The first time the next button link is clicked, I want to remove the off class, to show it as clickable, I probably should disable the link initially too and re-enable it too.
$(".back-btn").removeClass("off");
Once I display the last div, I need to add the off class to the next-btn and disable it.
I thought about using a carousel js plugin to accomplish this, but it is overkill for now.
I know of a way to do this, but it would involve assigning subclasses to the links based on what next or back button was clicked, so it will know what div to show next, as well as removing or adding the off class to the links.
I am hoping to find a solution that allows me to add more div's to display without modifying the code. Any help is appreciated, thank you.
Here is solution for you. I have created Fiddle for your requirement.
HTML code:
<a class="back-btn off">Back</a> | <a class="next-btn">Next</a>
<div class="vote-result first selectedDiv">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result last">
this is the last div
</div>
JS/JQuery Code:
$(".back-btn").click(function(){debugger;
var prevElement=$('.selectedDiv').prev();
prevElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
prevElement.addClass("selectedDiv");
if($('.first').css('display')=="block"){
$(".back-btn").addClass("off");
}
else{
$(".next-btn").removeClass("off");
}
});
$(".next-btn").click(function(){debugger;
var nextElement= $('.selectedDiv').next();
nextElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
nextElement.addClass("selectedDiv");
if($('.last').css('display')=="block"){
$(".next-btn").addClass("off");
}
else{
$(".back-btn").removeClass("off");
}
});
CSS code:
.vote-result { display: none; }
.vote-result.first { display: block; }
.off{display:none;}
Your HTML file:
<html>
<head>
<style>
.vote-result { display: none; }
.vote-result.first { display: block; }
.off {
color: Red;
}
a {
color: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="code.js"></script>
</head>
<body>
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
</body>
</html>
Your new "code.js" file in the same directory:
/**
* The zero-based index of the <div class="vote-result"> element that is currently being shown
* #var {Number}
*/
var activeIndex = 0;
function getNumberOfItems() {
return $('.vote-result').length;
}
function synchronizeInterface() {
var numberOfItems = getNumberOfItems(),
lastIndex = numberOfItems - 1;
$('.vote-result').removeClass('first');
$('.vote-result').each(function(index) {
if (index == activeIndex) {
$(this).addClass('first');
}
})
$('.back-btn').toggleClass('off', activeIndex == 0);
$('.next-btn').toggleClass('off', activeIndex == lastIndex);
}
$(function() {
$('.back-btn,.next-btn').on('click', function() {
// If the button clicked is not deactivated
if (!$(this).hasClass('off')) {
// Determine whether the "Next" button was clicked (otherwise "Back" was clicked)
var clickedNext = $(this).hasClass('next-btn');
// Move the active index in the appropriate direction while not allowing it to fall outside the boundaries of appropriate indices
activeIndex = clickedNext
? Math.min(activeIndex + 1, getNumberOfItems() - 1)
: activeIndex = Math.max(0, activeIndex - 1);
// Make sure the interface now reflects the updated JavaScript variables
synchronizeInterface();
}
return false;
});
});
Some notes: You had an unclosed double-quote for one of your class attributes in your provided HTML. Also, I added some additional styling -- you may want to rename the ".first" CSS class to ".active" instead.
take a look at jquerys .next() function for navigating - jQuery - Next(). you can also check for the last item like this.
if($(this).is(':last-child'))
{
$('.next-btn').removeClass('off');
}else{
$('.next-btn').addClass('off');
}
check everytime a navigation button is clicked and do the same for the first button

jQuery toggle 3 Div

I wanna toggle 3 div.
In the start situation I have the first div that is not trigger able for the clic because its ID.
When I click the second or third div (triggered), the DIV clicked have to become unclickable and the others 2 clickable.
I attach my live example:
http://jsfiddle.net/YV3V5/
HTML:
<div id = "not-selectable" class = "btn1">Div 1</div>
<div id = "selectable" class = "btn2">Div 2</div>
<div id = "selectable" class = "btn3">Div 3</div>
JAVASCRIPT:
$( "#selectable" ).click(function(e) {
var className = $(this).attr('class');
alert(className);
if (className == "btn1") {
$("btn1").attr("selectable","not-selectable");
$("btn2").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn2") {
$("btn2").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn3") {
$("btn3").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn2").attr("not-selectable","selectable");
}
});
In this situation when I click the second DIV, it should became unclickable....but nothing happens.
Thanks for you're help!
You have several errors in your code. The most important being that IDs should be unique. Secondly you are trying to assign values to attributes "selectable" and "not-selectable". These attributes do not exist.
If you lay out your markup correctly, you could do this pretty simple. I would suggest something like this:
HTML
<div class="buttons">
<div class="button">Div 1</div>
<div class="button selectable">Div 2</div>
<div class="button selectable">Div 3</div>
</div>
jQuery
$( ".buttons" ).on("click",".selectable",function(e) {
$('.button').addClass('selectable');
$(this).removeClass('selectable');
});
Can be tested here
(I've added a parent element to simplify event delegation in jQuery.)
there is no attribute called selectable for html tags.
when you write $("btn3").attr("selectable","not-selectable"); it means set the selectable attribute of btn3 to value 'not-selectable'.
also as btn3 is a class you should have written $('.btn3') instead of $('btn3')
WORKING DEMO http://jsfiddle.net/YV3V5/23/
There was a lot wrong with your code :
1) using duplicate id's : Id's must be unique , one per page. Classes do not have to be unique. So I changed around your id's and classes.
2) you should change classes with addClass/removeClass/or toggleClass
3) you shouldn't use a class your removing as the trigger of the click function, so I gave them all a same class of btn.
html :
<div id="btn1" class="not-selectable btn">Div 1</div>
<div id="btn2" class="selectable btn">Div 2</div>
<div id="btn3" class="selectable btn">Div 3</div>
css I added background of blue for selectable and red for not-selectable so easier to visualize what's happening:
.selectable {
background: blue;
}
.not-selectable {
background: red;
}
jquery :
$(document).ready(function () {
$(".btn").click(function (e) {
var id = $(this).attr('id');
if (id == "btn1") {
$("#btn1").removeClass("selectable").addClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn2") {
$("#btn2").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn3") {
$("#btn3").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
}
});
});
.attr() sets the attribute to the tags. So like you would get <div non-selectable='selectable'> for that code. Here is the documentation. I would use .removeClass() and .addClass() though there might be a more efficient way.

How can I hide a specific element that is outside of .each() Jquery

By Sharepoint a bunch of tds get generated with a few elements inside of them. So just to be clear I cant edit or change elements since it gets generated.
What I want to accomplish is to iterate throught all '.js-contentFollowing-itemLink' and then if the .text() contains the specific text I am looking for the '<span> Stop following</span>' should become hidden with '.hide()'.
I cant seem to accomplish this I have tried many ways.
Here is the jsfiddle:
http://jsfiddle.net/QXwyk/3/
Also take notice that I cant grab a id that is unique and many of these elements are generated with different values and texts.
HTML:
<span class="ms-contentFollowing-itemTitle">
test
</span>
<br>
<div class="js-contentFollowing-itemUrlDiv">
<span class="ms-metadata ms-contentFollowing-itemUrl"></span>
<input type="text" readonly="readonly" class="ms-metadata ms-contentFollowing-itemUrl ms-contentFollowing-itemFullUrl" style="visibility: visible; border-color: transparent; background-color: transparent;">
</div>
<span>Stop following</span>
My JS:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
$(this).closest("span").hide();
});
Note: I know it hides wrong element but the If statement works its the code inside the if statement that I cant accomplish I need to hide ' Stop following'. This JS is just one of the examples I have done that is not working.
I tried with $('.ms-secondaryCommandLink span').hide(); inside the if statement but that removed all <span> with "Stop following" :/
Thanks a bunch!
Several issues in your code:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
var text = $(this).parent().parent().parent().hide); <-- hide not closed properly
} <--- Extra bracket here..
});
Working code:
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test") {
var text = $(this).parent().parent().parent().hide();
}
});
Html
<div class="ms-content">
<span class="ms-contentFollowing-itemTitle">
test
</span>
<br>
<div class="js-contentFollowing-itemUrlDiv" id="contentFollowingUrl_18" url="http://dev/socialsites/Utförsåkning">
<span class="ms-metadata ms-contentFollowing-itemUrl"></span>
<input type="text" readonly="readonly" class="ms-metadata ms-contentFollowing-itemUrl ms-contentFollowing-itemFullUrl" style="visibility: visible; border-color: transparent; background-color: transparent;">
</div>
<span>Stop following</span>
</div>
JS
$('.js-contentFollowing-itemLink').each(function () {
if ($(this).text() == "test")
var text = $(this).closest('.ms-content').find('.ms-secondaryCommandLink').hide();
});
http://jsfiddle.net/QXwyk/4/
You can select the object containing specific text by following way,based on which you can can do remaining actions ...
Example: $('.js-contentFollowing-itemLink:contains(test)').hide(); will hide "test"

JQuery toggle Q&A: individual Q&As don't operate correctly unless you click on Open All/Close All first

I have a Q&A list with "Open All/Close All" at the top with individual open and close image buttons that toggle when clicked. That works fine.
Then follow individual Q&As, and each has its own open and close image.
If you click on "Open All/Close All" first, as soon as the page loads, and then click on the individual Q&A open/close images, all works fine. But if after page load you click on the individual Q&A open/close images, bypassing "Open All/Close All," they display the inappropriate open or close image.
Here is page code:
<div class="answersee"><span>Open All</span><img src="assets/open.gif" border="0" alt="" /></div>
<div class="answerhide"><span>Close All</span><img src="assets/close.gif" border="0" alt="" /></div>
<div class="qa">
<div><img src="open.gif" border="0" alt="" /><span class="question">Question.</span></div>
<div class="answer"><p>Answer.</p></div>
</div>
Here's the script (also uses Jquery):
$(function () {
$(".qa").click(function () {
$(this).find("div").next().slideToggle("fast");
if ($(this).find("div:eq(0)").find("img").attr("src") == "open.gif") {
$(this).find("div:eq(0)").find("img").attr("src", "close.gif");
}
else {
$(this).find("div:eq(0)").find("img").attr("src", "open.gif");
}
});
$(".answersee").click(function () {
$(".answer").show("fast");
$(".qa > div > img").attr("src", "close.gif");
$(".answerhide").show();
$(".answersee").hide();
})
$(".answerhide").click(function () {
$(".answer").hide("fast");
$(".qa > div > img").attr("src", "open.gif");
$(".answersee").show();
$(".answerhide").hide();
})
});
I don't think it's a CSS problem, or I'd include that code here. Do I need to initialize the script in some way? Or did I make a mistake in the above script?
Here's how I would do it.
Working Demo →
EDIT:
Update the code to have simple open/close link.
Code with comments which explains my approach:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
body
{
font-family: "Verdana";
font-size: 12px;
}
.question
{
background-color: #ccc;
cursor: pointer;
padding: 5px;
margin-bottom: 10px;
border-bottom: 1px solid #000;
}
.answer {
padding: 5px;
}
</style>
<script>
$(document).ready(
function()
{
//Hide all the answers on page load.
$('.answer').hide();
//For all questions, add 'open'/'close' text.
//You can replace it with an image if you like.
//This way, you don't need to specify img tag in your HTML for each question.
$('.question')
.append(' <span>[ open ]</span>');
//Now there are two ways to toggle the visibility of answer.
//Either click on the question OR click on Open All / Close All link.
//To use the same code for both instances, we will create
//a function which will take the 'question' div and toggle the answer for it.
//Advantage of this approach is that the code to toggle the answer is in
//one place.
//By default, this function will try to toggle the status of the answer
//i.e. if it's visible, hide it otherwise show it.
//This function will take a second argument called 'showAnswer'.
//If this argument is passed, it overrides the toggle behavior.
//If 'showAnswer' is true, answer is shown.
//If it's false, answer is hidden.
//This second parameter will be used by the 'openAll', 'closeAll' links.
var toggleAnswer = function toggleAnswer(question, showAnswer)
{
//The way I have structured the HTML, answer DIV is right after
//question DIV.
var $answer = $(question).next('div');
//Animation callback, after the animation is done, we want to
//switch the 'text' to display what could the user do with the question.
//Once again, you can change this code to show open/close image.
var updateText = function()
{
var text = $answer.is(':visible') ? ' [close] ' : ' [open] ';
$(question).find('span').html(text);
}
var method = null;
if(arguments.length > 1)
{
//If the function was called with two arguments, use the second
//argument to decide whether to show or hide.
method = showAnswer === true ? 'show' : 'hide';
}
else
{
//Second argument was not passed, simply toggle the answer.
method = $answer.is(':visible') ? 'hide' : 'show';
}
$answer[method]('fast', updateText);
};
//On each question click, toggle the answer.
//If you have noticed, I didn't enclose both Q&A inside one DIV.
//The way you have done if user clicks on the answer, answer will collapse.
//This may not be desirable as user may want to copy the answer
//and he won't be able to.
$('.question').click(function(){ toggleAnswer(this);});
//We will reuse the same toggleAnswer method in openAll, closeAll
//handling. This way, if you want to change behavior of how the question/answers
//are toggled, you can do it in one place.
$('#openClose').click(
function()
{
var showAnswer = $(this).html().toLowerCase().indexOf('open') != -1 ? true : false;
$('.question').each(function() { toggleAnswer(this, showAnswer); });
$(this).html(showAnswer ? 'Close All' : 'Open All');
return false;
}
);
}
);
</script>
<html>
<head>
<title>simple document</title>
</head>
<body>
<a id='openClose' href='#'>Open All</a>
<br /><br />
<div class='question'>Question 1</div>
<div class='answer'>Answer 1</div>
<div class='question'>Question 2</div>
<div class='answer'>Answer 2</div>
<div class='question'>Question 3</div>
<div class='answer'>Answer 3</div>
</body>
</html>
You need to use the callbacks because your animation will not have finished by the time to check for which image is being shown.
$(".qa").click(function() {
$(this).find("div").next().slideToggle("fast", toggleImage);
}
function toggleImage(){
var $img = $(this).find("img");
$img.attr('src') == "open.gif" ? $img.attr('src', "close.gif") : $img.attr('src', "open.gif");
}
N.B There are better ways to do this but lets get you working first and then see if you want to refactor it some more.
Thank you for taking the time to provide this. I will try this later today and report back. In my version, I toggle the Open All/Close All feature. It's a cleaner look and easier to use, since you don't have to move your mouse.
Redsquare and Solution Yogi:
Thanks. I will reply again later and also post a working demo so you can see the problem more clearly. Sorry, I should have done that before.
Liz

Categories

Resources