jQuery hide text, display on hover?
Asked Answered
C

2

5

Hopefully just a quick question :)

I'm trying to write little jQuery that will help do this:

  • text displayed on page: CA
  • text displayed when mouse hovers: CALIFORNIA

I've managed to do this the wrong way round unfortunately, I know I need to use the .hide() function but I just can't figure out how to use it. Sorry I'm pretty new to jQuery and just trying to get my head round it.

Here's a jfiddle I made link, preferably the text would slide in from the right. I've tried using a span but it seemed to work better having p tags in different divs. I understand that I'll need to put the HTML all on one line to get rid of the little space between CA and LIFORNIA. could anyone possibly please assist?

HTML:

<div class="state">
     <p>CA</p>
</div>
<div class="state-full">
     <p>LIFORNIA</p>
</div>

CSS:

.state, .state-full {
     display: inline-block;
     cursor: pointer;
}

jQuery:

$('.state').hover(function() {
     $('.state-full').slideToggle(100, 'linear');
     $('.state-full').display(100, 'linear');
});

Many thanks!

Constantinople answered 7/12, 2012 at 11:0 Comment(0)
M
7

The code you had would work fine, you just need to modify your HTML and CSS a little to make it more semantic. Try this:

<div class="state">      
    <span>CA</span>
    <span class="state-full">LIFORNIA</span>
</div>
.state, .state-full { cursor: pointer; }
.state-full { display: none; }
.state span { float: left; }
$('.state').hover(function() {
    $('.state-full', this).slideToggle(100, 'linear').display(100, 'linear');
});

Note that I added a context to the selector as I assume you're going to have more than one of these on the page.

Example fiddle

Mesa answered 7/12, 2012 at 11:18 Comment(1)
Many thanks guys, much appreciated. they both work great but I went with @Rory's answer in the end as it means I can do multiple 'state' divs without having to repeat the jquery over and over. I'm sure they'll both come in handy though! :)Constantinople
N
3

Try this:

<script type="text/javascript">
    $(document).ready(function () {
        $('.state').mouseenter(function () {
            $(this).html("CALIFORNIA");
        });
        $('.state').mouseleave(function () {
            $(this).html("CA");
        });
    });
</script>

Hope it helps :)

Numbskull answered 7/12, 2012 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.