Search code examples
jquerygraphical-logoletter

Replacing one letter with an image without destroying text flow with Jquery


Object: I have a header title from which I want to replace only one letter with an image logo.

Problem: After working with <span> it somehow destroys my design, I means it breaks lines, does not properly replace the letter but appears somewhere else. I know it is the positioning but a lot of approaches went straight down the drain. Anyone has an idea?

My script, quite basic:

<script type="text/javascript">
      $(function() {
            $('#logo span').fadeOut(7000);
            $('#logo span 2').fadeIn(2000);
      });
    </script> 

My css:

 <style>
     #logo .span 2 {display:none}
    </style>

My html:

<!-- Header & Call to Action Area -->
<div id="logo"><a href="index.html">Mundo<img class="logo" src="pictures/logos/logo_mundo_krone_header.png" width="100" height="56" alt="logo kundo gourmet puerto varas,restaurant puerto varas,puerto varas lujo,extravagante puerto varas" /><br />Gour<span><span class="2"><img src="pictures/logos/logo_mundo_krone_header.png" width="100" height="56" /></span>m</span>et</a></div>

Solution

  • Ahh...I see what's wrong here. you're saying span 2, literally. That is not a valid selector. What you need to do is the following.

    $('#logo span').eq(0).fadeOut(7000);
    

    jQuery uses zero based indexing. here we're telling jQuery we want the first span to fade out.

    $('#logo span').eq(1).fadeIn(2000);
    

    Here we tell the 2nd span to fade in.

    Generally speaking, these types of effects are combined together using callback functions.

    $('#logo span').eq(0).fadeOut(7000, function(){
        //this is the callback function.
        //when the above fade completes, anything in here will run immediately after.
        $('#logo span').eq(1).fadeIn(2000);
    });
    

    As a side note to anyone coming here in the future

    I've used jQuery's .eq() which is a sizzle selector, instead of jQuery's :eq() which is a jQuery selector. The reason being is that sizzle selectors can leverage the querySelectorAll() method, where pure jQuery selectors must traverse the DOM to find the element. While for the example above this probably isn't going to yield much in savings, on the whole if you do alot of traversing, this key note is important.