Felix Perez
Felix Perez

Reputation: 33

JavaScript clicking letter displays text issue

I want to have something of an easter egg in my website. If you click the letter f in the word food, a picture of brownies appears. I can click the letter f and the brownies appear, but the issue is that the word food does not appear as one word it appears with a break between f and ood.

I have a JSfiddle to demonstrate: http://jsfiddle.net/od88txko/

My code:

$( document ).ready(function() {
    $('.f').on('click', function () {
        $('div', this).text(function (text) {
            return text === 'f' ? 'f' : 'f';
        }).parent().next().toggle();
    }); 
});

Upvotes: 3

Views: 96

Answers (3)

Dan
Dan

Reputation: 9468

Change your HTML to this:

<span class="f">f</span>ood

JS Fiddle Demo (I also edited your JS to reflect the HTML change)

Ok so as noted in other responses that's because <div> is a block level element. As explained by Mozilla (bold added for emphasis):

"Block-level" is categorization of HTML (Hypertext Markup Language) elements, as contrasted with "inline" elements. Block-level elements may appear only within a element. Their most significant characteristic is that they typically are formatted with a line break before and after the element (thereby creating a stand-alone block of content). That is, they take up the width of their containers.

Upvotes: 8

Thad Blankenship
Thad Blankenship

Reputation: 2302

That's because you are using a div, which is a block element. You want an inline element, such as span

Upvotes: 4

Daniel Sanchez
Daniel Sanchez

Reputation: 263

That's because a DIV is a block-level element. try using SPAN instead

Upvotes: 2

Related Questions