I've code few line of jQuery for Hide/Show many elements on single click and it's working. But problem is; i've many more image class items, so my script going to long, my question is how to simplify or make short my script, i mean any alternatives or any new idea? please suggest.
HTML:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- many many images -->
</span>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
JS: live demo >
$("button.red").click(function(){
$(".images-red").show();
$(".images-blue, .images-pink").hide();
});
$("button.blue").click(function(){
$(".images-red, .images-pink").hide();
$(".images-blue").show();
});
$("button.pink").click(function(){
$(".images-red, .images-blue").hide();
$(".images-pink").show();
});
Please suggest for short and simple code of my script. Thanks.
You can do it by adding just a common class to those buttons,
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().eq($(this).index("button.button")).show();
});
The concept behind the code is to bind click event for the buttons by using the common class. Now inside the event handler, hide all the i elements which has been cached already and show the one which has the same index as clicked button.
DEMO
For more details : .eq() and .index(selector)
And if your elements order are not same, both the i and button's. Then you can use the dataset feature of javascript to over come that issue.
var iTags = $("#choose-color span i");
$("#choose-color button.button").click(function(){
iTags.hide().filter(".images-" + this.dataset.class).show()
});
For implementing this you have to add data attribute to your buttons like,
<button data-class="red" class="button red">Red</button>
DEMO
This works
$("#choose-color button").click(function(){
var _class = $(this).attr('class');
$("#choose-color i").hide();
$(".images-"+_class).show();
});
https://jsfiddle.net/455k1hhh/5/
I know this might not be the prettiest solution, but it should do the job.
$("button").click(function(){
var classname = $(this).attr('class');
$("#choose-color span i").hide();
$(".images-"+classname).show();
});
You're making future extensibility a little difficult this way due to relying on class names but this would solve your immediate need:
<div id="myImages">
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</div>
<div id="myButtons">
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
$("#myButtons button").click(function(){
var color = $(this).attr("class");
var imageClass = ".images-"+color;
$('#myImages').children("i").each(function () {
$(this).hide();
});
$(imageClass).show();
});
Here's a JSFiddle
Edit: Note how I wrapped the buttons and images in parent divs to allow you to isolate just the buttons/images you want to work with.
You can do the following using data-* attributes, because when you have more elements of the same color, using index of the button won't work. And simply using the whole class attribute won't work if you have to add more classes to the button in future.
$("button").click(function() {
var color = $(this).data('color');
var targets = $('.images-' + color);
targets.show();
$("span i").not(targets).hide();
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<br/>
<div id="choose-color">
<span>
<i class="images-red">Red Image</i>
<i class="images-blue hidden">Blue Image</i>
<i class="images-pink hidden">Pink Image</i>
<!-- Many many image -->
</span>
<br/>
<br/>
<button data-color="red">Red</button>
<button data-color="blue">Blue</button>
<button data-color="pink">Pink</button>
</div>
It would make sense to have all images share a single class (.image for example). Then you just use a shared class for the button and the image; in this example I used the color name. Now, when any button is clicked, you can grab the class name of the image you want to show.
Give this a try:
$("button").click(function(){
$(".image").hide();
var className = $(this).attr("class");
$("." + className).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/><br/>
<div id="choose-color">
<span>
<i class="image red" style="">Red Image</i>
<i class="image blue" style="display: none;">Blue Image</i>
<i class="image pink" style="display: none;">Pink Image</i>
<!-- Many many image -->
</span>
<br/><br/>
<button class="red">Red</button>
<button class="blue">Blue</button>
<button class="pink">Pink</button>
</div>
You may try this:
<div id="choose-color">
<span>
<i class="images-red" style="">Red Image</i>
<i class="images-blue" style="display: none;">Blue Image</i>
<i class="images-pink" style="display: none;">Pink Image</i>
<!-- Many image -->
</span>
<br/><br/>
<button class="colour red" onclick="myFunction(this)">Red</button>
<button class="colour blue" onclick="myFunction(this)">Blue</button>
<button class="colour pink" onclick="myFunction(this)">Pink</button>
</div>
JS: see here
$(".colour").click(function(){
var colors = ["red", "blue", "pink"];
for (i = 0; i < colors.length; i++) {
if($(this).hasClass(colors[i])){
$(".images-"+colors[i]).show();
}else{
$(".images-"+colors[i]).hide();
}
}
});
Related
I'm creating a page for a company where they have pictures of the 4 founders all side by side. The text under all 4 images needs to change based on what photo is clicked or hovered on. So one says "mark" in bold and under that it will have his qualifications. But that will all be replaced when I click "kim" who is the next picture.
I'm very new to HTML, CSS, and have never tried javascript so this is my first attempt.
I want the text to be styled the way I want, but I can't find a way to update it all. I only figured out that I can print raw text.
Is there a way to call a div to put the text there and replace it with a new div for each image click?
Like instead of writing .html("Mark does xyz") you could instead paste in the entire div "tr1" with the changed button and heading and paragraph?
<div id="trainers">
<h1><b>Meet Our Trainers</h1>
<img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%">
<img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%">
<div id="tr1">
<h1><b><br>Mark</b></h1>
<p>Mark has been a personal trainer</p>
<a class="btn" href="#">Book With Mark</a>
</div>
<div id="tr2">
<h1><b><br>Kim</b></h1>
<p>Kim is a nutritionist</p>
<a class="btn" href="#">Book With Kim</a>
</div>
</div>
<script>
$('#Mark').click(function() {
});
$('#Kim').click(function() {
});
</script>
You can use show/hide method for your requirement.
$('#Mark').click(function() {
$('#tr1').show();
$('#tr2').hide();
});
$('#Kim').click(function() {
$('#tr1').hide();
$('#tr2').show();
});
$('#Mark').click(function() {
$('#tr1').show();
$('#tr2').hide();
});
$('#Kim').click(function() {
$('#tr1').hide();
$('#tr2').show();
});
#tr2{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trainers">
<h1><b>Meet Our Trainers</h1>
<img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%">
<img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%">
<div id="tr1">
<h1><b><br>Mark</b></h1>
<p>Mark has been a personal trainer</p>
<a class="btn" href="#">Book With Mark</a>
</div>
<div id="tr2">
<h1><b><br>Kim</b></h1>
<p>Kim is a nutritionist</p>
<a class="btn" href="#">Book With Kim</a>
</div>
</div>
$('#Mark').click(function() {
var elementToClone = document.getElementById('tr1');
var clone = elementToClone.cloneNode(true);
var container = document.getElementById('container');
// Then you need to append that cloned element into a container on the page.
container.appendChild(clone);
});
The container will be en element in your HTML that currently is not there. This is just a place where you want this cloned HTML to go:
<div id="container></div>
This will get you to a point where you've copied the HTML you need and placed it where you want it on the page. When you click a different image, you'll need to remove this HTML, clone the other HTML and append it to container. You'll also probably need an if statement in there to check if container contains something already.
You're using jQuery in your question, so this answer uses the jQuery click function -- if you don't have jQuery included, you'll need it.
You can also use these vanilla js click methods:
<img id="Mark" onclick="doHTMLAppendFunction()" src="foo.jpg" />
or
document.getElementById('Mark').addEventListener('click', doHTMLAppendFunction);
You're trying to use JQuery to achieve this and following does the job. There used the common class "trainer-text" to hide all overlay texts to hide at the initial point. Use some css to make the text on your images. Refer the following to achieve that. https://www.w3schools.com/howto/howto_css_image_overlay.asp
/*
Use the following if you need display text for hover event
*/
$("#Mark").mouseover(function(){
$("#tr1").css("display", "block");
});
$("#Mark").mouseout(function(){
$("#tr1").css("display", "none");
});
$("#Kim").mouseover(function(){
$("#tr2").css("display", "block");
});
$("#Kim").mouseout(function(){
$("#tr2").css("display", "none");
});
/*
Use the following if you need display text for click event
*/
$('#Mark').click(function() {
$('#tr1').show();
$('#tr2').hide();
});
$('#Kim').click(function() {
$('#tr1').hide();
$('#tr2').show();
});
.trainer-text {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trainers">
<h1><b>Meet Our Trainers</b></h1>
<img src="jackf.jpg" id="Mark" alt="Mark" width="17%" height="40%"/>
<img src="kimsond.jpg" id="Kim" alt="Kim" width="17%" height="40%"/>
<div id="tr1" class="trainer-text">
<h1><b><br>Mark</b></h1>
<p>Mark has been a personal trainer</p>
<a class="btn" href="#">Book With Mark</a>
</div>
<div id="tr2" class="trainer-text">
<h1><b><br>Kim</b></h1>
<p>Kim is a nutritionist</p>
<a class="btn" href="#">Book With Kim</a>
</div>
</div>
I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});
I am trying to remove the $movieDiv that is appended when clicking "#buttonLicensedMovie". It appends to the html just fine and the same button hides just fine, as it should. The issue I am having is when I click the anchor tag with id "licensedMovie1, the $movieDiv does not remove and the "#buttonLicensedMovie1" does not show back up. What am I doing wrong? Any help would be appreciated. Thanks!
JQuery:
$(function() {
$("#buttonLicensedMovie1").click(function(){
var $movieDiv = '<p class="header">Becoming An Agent</p>\n<iframe width="500" height="281" src="https://www.youtube.com" frameborder="0" allowfullscreen></iframe>\r\n<br/><a id="licensedMovie1" class="video-close"><i class="fa fa-times" aria-hidden="true"></i> Close Video</a>';
$("#movieLicensedWrapper1").append($movieDiv);
$("#buttonLicensedMovie1").hide();
});
});
$(function() {
$("#licensedMovie1").click(function(){
var $movieDiv = '<p class="header">Becoming An Agent</p>\n<iframe width="500" height="281" src="https://www.youtube.com/" frameborder="0" allowfullscreen></iframe>\r\n<br/><a id="licensedMovie1" class="video-close"><i class="fa fa-times" aria-hidden="true"></i> Close Video</a>';
$("#movieLicensedWrapper1").remove($movieDiv);
$("#buttonLicensedMovie1").show();
});
});
HTML:
<div class="col-xs-12">
<button id="buttonLicensedMovie1" type="button" class="btn btn-default"><h5>Becoming an Agent <i class="fa fa-caret-square-o-right fa-lg" aria-hidden="true"></i></h5></button>
<div class="col-xs-12" id="movieLicensedWrapper1">
</div>
</div>
You could use (won't work in your case because not everything is inside the p):
$("#movieLicensedWrapper1 p.header").remove();
Or you create a global variable and assign the value with:
$movieDiv = $.parseHTML('...');
And then you can remove with just:
$movieDiv.remove();
When you append it works fine because you are just adding html. However, when you want to remove you need to select the DOM element. Try this instead:
var $movieDiv = $('#movieLicensedWrapper1').find('.header');
$movieDiv.remove();
Simply put, trying to push simple answer values to a jquery array.
HTML
<div class="answer-A">
<a href="#question2" value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#question2" value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#question2" value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
Jquery
var finalAnswers = [''];
$(document).ready(function () {
$('.answer-A').finalAnswers.push();
console.log(finalAnswers);
});
Probably shouldn't be using value - there's probably a much easier way?
If I understood correctly your question, I created this fiddle with an approach to accomplish your task:
https://jsfiddle.net/mrlew/hvr9ysq6/
html:
<div class="answer-A">
<a href="#" data-value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#" data-value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#" data-value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
js:
var finalAnswers = [];
$(document).ready(function () {
$("a[data-value]").on("click", function(e) {
var value = $(this).attr('data-value');
finalAnswers.push(value);
alert("Answers so far: " + finalAnswers.join(","));
e.preventDefault();
});
});
Here is example for your comment about how you want to push the value that user click.
var finalAnswers = [];
$(".answer-A, .answer-B, answer-C").click(function(){
var value = $(this).children("a").attr("value");
finalAnswers.push(value)
});
Use a selector that matches divs with class that start with answer and their anchor children
div[class^="answer-"] a
Iterate through these elements and get their value attribute. Like this:
var finalAnswers = [''];
$(document).ready(function () {
$('div[class^="answer-"] a').each(function(i,v){
finalAnswers.push($(v).attr("value"));
});
console.log(finalAnswers);
});
Fiddle
https://jsfiddle.net/1gmn1w1b/
I am using Twitter Bootstrap to create collapsible sections of text. The sections are expanded when a + button is pressed. My html code as follows:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button type="button" class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
Is there a way to change the button to display - instead of + after the section is expanded (and change back to + when it is collapsed again)?
Additional information: I hoped there would be a simple twitter-bootstrap/css/html-based solution to my problem. All responses so far make use of JavaScript or PHP. Because of this I want to add some more information about my development environment: I want to use this solution inside a SilverStripe-based (version 3.0.5) website which has some implications for the use of both PHP as well as JavaScript.
try this. http://jsfiddle.net/fVpkm/
Html:-
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
JS:-
$('button').click(function(){ //you can give id or class name here for $('button')
$(this).text(function(i,old){
return old=='+' ? '-' : '+';
});
});
Update With pure Css, pseudo elements
http://jsfiddle.net/r4Bdz/
Supported Browsers
button.btn.collapsed:before
{
content:'+' ;
display:block;
width:15px;
}
button.btn:before
{
content:'-' ;
display:block;
width:15px;
}
Update 2 With pure Javascript
http://jsfiddle.net/WteTy/
function handleClick()
{
this.value = (this.value == '+' ? '-' : '+');
}
document.getElementById('collapsible').onclick=handleClick;
Here's another CSS only solution that works with any HTML layout.
It works with any element you need to switch. Whatever your toggle layout is you just put it inside a couple of elements with the if-collapsed and if-not-collapsed classes inside the toggle element.
The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.
It also requires the :not selector, so it doesn't work on IE8.
HTML example:
<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
<!--You can put any valid html inside these!-->
<span class="if-collapsed">Open</span>
<span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
Less version:
[data-toggle="collapse"] {
&.collapsed .if-not-collapsed {
display: none;
}
&:not(.collapsed) .if-collapsed {
display: none;
}
}
CSS version:
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
JS Fiddle
Add some jquery code, you need jquery to do this :
<script>
$(".btn[data-toggle='collapse']").click(function() {
if ($(this).text() == '+') {
$(this).text('-');
} else {
$(this).text('+');
}
});
</script>
All the other solutions posted here cause the toggle to get out of sync if it is double clicked. The following solution uses the events provided by the Bootstrap framework, and the toggle always matches the state of the collapsible element:
HTML:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button id="intro-switch" class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
JS:
$('#intro').on('show', function() {
$('#intro-switch').html('-')
})
$('#intro').on('hide', function() {
$('#intro-switch').html('+')
})
That should work for most cases.
However, I also ran into an additional problem when trying to nest one collapsible element and its toggle switch inside another collapsible element. With the above code, when I click the nested toggle to hide the nested collapsible element, the toggle for the parent element also changes. It may be a bug in Bootstrap. I found a solution that seems to work: I added a "collapsed" class to the toggle switches (Bootstrap adds this when the collapsible element is hidden but they don't start out with it), then added that to the jQuery selector for the hide function:
http://jsfiddle.net/fVpkm/87/
HTML:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button id="intro-switch" class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...<br>
<a id="details-switch" class="collapsed" data-toggle="collapse" href="#details">Show details</a>
<div id="details" class="collapse">
More details...
</div>
</div>
</div>
JS:
$('#intro').on('show', function() {
$('#intro-switch').html('-')
})
$('#intro').on('hide', function() {
$('#intro-switch.collapsed').html('+')
})
$('#details').on('show', function() {
$('#details-switch').html('Hide details')
})
$('#details').on('hide', function() {
$('#details-switch.collapsed').html('Show details')
})
I liked the CSS-only solution from PSL, but in my case I needed to include some HTML in the button, and the content CSS property is showing the raw HTML with tags in this case.
In case that could help someone else, I've forked his fiddle to cover my use case: http://jsfiddle.net/brunoalla/99j11h40/2/
HTML:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">
<span class="show-ctrl">
<i class="fa fa-chevron-down"></i> Expand
</span>
<span class="hide-ctrl">
<i class="fa fa-chevron-up"></i> Collapse
</span>
</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
CSS:
button.btn .show-ctrl{
display: none;
}
button.btn .hide-ctrl{
display: block;
}
button.btn.collapsed .show-ctrl{
display: block;
}
button.btn.collapsed .hide-ctrl{
display: none;
}
My following JS solution is better than the other approaches here because it ensures that it will always say 'open' when the target is closed, and vice versa.
HTML:
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">
Open
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
JS:
$('[data-toggle-secondary]').each(function() {
var $toggle = $(this);
var originalText = $toggle.text();
var secondaryText = $toggle.data('toggle-secondary');
var $target = $($toggle.attr('href'));
$target.on('show.bs.collapse hide.bs.collapse', function() {
if ($toggle.text() == originalText) {
$toggle.text(secondaryText);
} else {
$toggle.text(originalText);
}
});
});
Examples:
$('[data-toggle-secondary]').each(function() {
var $toggle = $(this);
var originalText = $toggle.text();
var secondaryText = $toggle.data('toggle-secondary');
var $target = $($toggle.attr('href'));
$target.on('show.bs.collapse hide.bs.collapse', function() {
if ($toggle.text() == originalText) {
$toggle.text(secondaryText);
} else {
$toggle.text(originalText);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">
Open
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
JS Fiddle
Other benefits of this approach:
the code is DRY and reusable
each collapse button stays separate
you only need to put one change into the HTML: adding the data-toggle-secondary attribute
I guess you could look inside your downloaded code where exactly there is a + sign (but this might not be very easy).
What I'd do?
I'd find the class/id of the DOM elements that contain the + sign (suppose it's ".collapsible", and with Javascript (actually jQuery):
<script>
$(document).ready(function() {
var content=$(".collapsible").html().replace("+", "-");
$(".collapsible").html(content));
});
</script>
edit
Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle, or slideDown and slideUp... Imagine it's a slideToggle for the elements of class .collapsible, which reveal contents of some .info elements. Then:
$(".collapsible").click(function() {
var content=$(".collapsible").html();
if $(this).next().css("display") === "none") {
$(".collapsible").html(content.replace("+", "-"));
}
else $(".collapsible").html(content.replace("-", "+"));
});
This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.
Easier with inline coding
<button type="button" ng-click="showmore = (showmore !=null && showmore) ? false : true;" class="btn float-right" data-toggle="collapse" data-target="#moreoptions">
<span class="glyphicon" ng-class="showmore ? 'glyphicon-collapse-up': 'glyphicon-collapse-down'"></span>
{{ showmore !=null && showmore ? "Hide More Options" : "Show More Options" }}
</button>
<div id="moreoptions" class="collapse">Your Panel</div>
Some may take issue with changing the Bootstrap js (and perhaps validly so) but here is a two line approach to achieving this.
In bootstrap.js, look for the Collapse.prototype.show function and modify the this.$trigger call to add the html change as follows:
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
.html('Collapse')
Likewise in the Collapse.prototype.hide function change it to
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
.html('Expand')
This will toggle the text between "Collapse" when everything is expanded and "Expand" when everything is collapsed.
Two lines. Done.
EDIT: longterm this won't work. bootstrap.js is part of a Nuget package so I don't think it was propogating my change to the server. As mentioned previously, not best practice anyway to edit bootstrap.js, so I implemented PSL's solution which worked great. Nonetheless, my solution will work locally if you need something quick just to try it out.
You do like this.
the function return the old text.
$('button').click(function(){
$(this).text(function(i,old){
return old=='Read More' ? 'Read Less' : 'Read More';
});
});
Applied and working in Bootstrap 5.0.1.
Using simple jQuery
jQuery('button').on( 'click', function(){
if(jQuery(this).hasClass('collapsed')){
jQuery(this).html('+');
} else {
jQuery(this).html('-');
}
});
You can also use font awesome or HTML instead of +/- signs.