acctman
acctman

Reputation: 4349

div style / format being lost when using show / hide

I'm using a show / hide code below. i works fine buy text format is being lost. is there anyway to prevent this? I have some markup style and style sheet coding

    <div id="fillit"></div>

    <a href="javascript:void(0)" class="para">Sci Lit 1</a>
    <div class="details">text for sci lit 1</div> 
    <a href="javascript:void(0)" class="para">Sci Lit 2</a>
    <div class="details">text for sci lit 2</div>    
    <a href="javascript:void(0)" class="para">Sci Lit 3</a>
    <div class="details">text for sci lit 3</div>   

<style>
.inner-boxes .box3, .details1 {display:none;}
</style>
<script>
$(function(){
    $(".para").click(function(){
        $("#fillit").text($(this).next(".details1").text()); 
    });
    $(".details1:first").clone().appendTo("#fillit").show();    
});
</script>

Upvotes: 1

Views: 678

Answers (2)

James Khoury
James Khoury

Reputation: 22319

in your script you have:

$(".para").click(function(){
    $("#fillit").text($(this).next(".details1").text()); 
});

Change to:

$(".para").click(function(){
    $("#fillit")
        .children(".details1")
        .replaceWith(
            $(this).next(".details1").clone().show()
        ); 
});

.text() only gets the inner text of the element

NOTE: As it has been noted in the comments, this is not the only way and might not even be the quickest. (I haven't done any tests on it myself) But it seems to me that it is all about style. The Pros of my answer is that the solution could work in a large number of different scenarios.

Upvotes: 0

ryanmarc
ryanmarc

Reputation: 1680

use .html() instead of .text()

change:

$("#fillit").text($(this).next(".details1").text());

to:

$("#fillit").html($(this).next(".details1").html());

Here is an example

Upvotes: 4

Related Questions