Reputation: 11052
Example fiddle - http://jsfiddle.net/S6CwT/
CSS
#service_container {
display: none;
}
HTML
<a href="/services/update/8" id="view_service">View Service Record</a>
<div id="service_container">
Test
</div>
jQuery
jQuery.noConflict();
jQuery(function() {
// toggle visibility of service section
jQuery('#view_service').click(function() {
jQuery('#service_container').slideToggle('slow');
// toggle text
if (jQuery('#service_container').is(':visible')) {
jQuery('#view_service').text('Hide Service Record');
} else {
jQuery('#view_service').text('View Service Record');
}
return false
});
});
The bug is when clicking the link for the first time, the link text will change correctly to say Hide Service Record
but on subsequent clicks the text will not change to Show Service Record
when the div
is hidden and back to Hide Service Record
when the container is visible again.
Must be something silly I'm not spotting but can't see what I've done wrong.
I tried it the opposite way using is(:hidden)
but that behaves the same way.
Upvotes: 0
Views: 116
Reputation: 530
Try This
jQuery(function() {
jQuery("#service_container").hide();
// toggle visibility of service section
jQuery('#view_service').click(function()
{
// toggle text
if (jQuery('#service_container').is(':visible'))
{
jQuery('#view_service').text('View Service Record');
}
else
{
jQuery('#view_service').text('Hide Service Record');
}
jQuery('#service_container').slideToggle('slow');
return false
});
});
Upvotes: 2
Reputation: 3572
The problem is that the '#service_container' is visible when the question is asked because it's not invisible until after the slideToggle()
completes. One solution would be to pass the logic to change the name in as a function to be run after the slideToggle()
has completed.
...
var changeText = function() { <visibility text change logic> };
jQuery('#service_container').slideToggle('slow', changeText);
...
EDIT: reference saved fiddle.
Full code: http://jsfiddle.net/rqGBb/1/
If you want the text to change immediately on click, you'll have to track the 'show/hide' status yourself in a variable, hang off the element, or test visibility in an outer if
block.
Upvotes: 1
Reputation: 30985
if (jQuery('#view_service').html()=="View Service Record") {
fiddle : http://jsfiddle.net/S6CwT/2/
I compare html of #view_service
Upvotes: 1
Reputation: 32581
Try this, show/hide in the if statement
if (jQuery('#service_container').is(':visible')) {
jQuery(this).text('View Service Record');
jQuery('#service_container').hide('slow');
} else {
jQuery(this).text('Hide Service Record');
jQuery('#service_container').show('slow');
}
Upvotes: 1
Reputation: 11741
try to use "on" event for future changes on any event as below
jQuery('#view_service').on("click",function() {
// your code..
}
Upvotes: 1