Steve Jones
Steve Jones

Reputation: 117

Can I change the text content in a <span> based on the width of the <span>?

As the width of my screen decreases for a smaller mobile device I would like to be able to change the sentence I have in my to a shorter sentence so it will fit on one line.

Essentially I would like to have the text when the:
-width is > 350px say "this is my text in the span"
-width is < 350px saw "this is span text"

Is this possible somehow?

Upvotes: 2

Views: 1785

Answers (3)

Brusooo
Brusooo

Reputation: 81

Gotcha!

Take a span alone and leave the text-content empty like this

<span class="magic_span"></span>

and now in css

.magic_span::after{
    content: "this is span text";
}

@media screen and (min-width : 350px){
    .magic_span::after{
        content: "this is my text in the span";
    }
}

Upvotes: 0

Pepo_rasta
Pepo_rasta

Reputation: 2900

or via CSS:

.over350 {
    display: inline;
}
.below350 {
    display: none;
}
@media screen and (max-width: 350px) {
    .over350 {
        display: none;
    }
    .below350 {
        display: inline;
    }
}
<span class="over350">this is my text in the span</span>
<span class="below350">this is span text</span>

Upvotes: 5

Rory McCrossan
Rory McCrossan

Reputation: 337580

You can achieve this by hooking to the resize event of the window, and inspecting the width of your span there. Try this:

$(window).resize(function() {
    $('.mySpan').text(function() {
        return $(this).width() >= 350 ? 'this is my text in the span' : 'this is span text';
    });
});

Upvotes: 6

Related Questions