Clicking a JavaScript button on the screen displays text

I want my site to have something like an Easter egg. If you hit the letter f in the word "food" a photo of brownies appears. I can click the f and the brownies appear, but the problem is that the word "food" does not appear as a single word that 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();
    }); 
});

      

+3


source to share


3 answers


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, as stated in other answers, because it <div>

is a block level element. As explained by Mozilla (in bold for emphasis):

"Block level" is a categorization of HTML (Hypertext Markup Language) elements as opposed to "inline" elements. Block level elements can only be displayed within an element. Their most important characteristic is that they are usually formatted with a line break before and after the element (thus creating a separate block of content) . That is, they occupy the width of their containers.

+8


source


This is because you are using div

which is a block element. You need an element inline

likespan



+4


source


This is because the DIV is a block level element. try using SPAN instead

+2


source







All Articles