Search code examples
javascriptjquerydatetimebusiness-catalyst

Replace spaces with <br /> on a date


I would like to replace the spaces on dateTime rendered text with <br /> tags.

The code I wrote will do that, except then all of my dates turn into the same date for some reason. I have no idea why this is occurring.

The platform this site is hosted on is Adobe Business Catalyst.

html:

<div class="panel callout radius columns small-12 medium-6 large-4 {tag_event month}" data-event-date="{tag_event date (for sorting)}">
    <div class="dateNumber" data-bc-date="format:MMM DD">{tag_event date (for sorting)}</div>
    <span><a href="{tag_itemurl_nolink}">{tag_short title}</a></span>
</div>

jQuery:

// If I run this, it will change all the rendered dates into Aug 7
$(".callout").each(function(){
    $(".dateNumber").html($(".dateNumber").html().replace(' ', '<br />'));
});

live Page: http://www.blackduckmn.com/calendar


Solution

  • jQuery's API is a bit quirky: Functions like html (and val and others) that can be both getters and setters are assymmetrical: When you're getting, they give you the value related to the first element in the set, but when you're setting, they set on all of the elements in the set.

    In this case, you can pass a function into html which will get called for each element:

    $(".callout .dateNumber").html(function(){
        return $(this).html().replace(' ', '<br />');
        // Or: return this.innerHTML.replace(' ', '<br />');
    });
    

    When you give html a function, it calls the function for each element and then sets the element's HTML to be whatever you return from the function.

    Full Example: Live Copy

    <!DOCTYPE html>
    <html>
    <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
      <meta charset="utf-8">
      <title>Example</title>
    </head>
    <body>
    <div class="panel callout radius columns small-12 medium-6 large-4">
        <div class="dateNumber" data-bc-date="format:MMM DD">Aug 07</div>
        <span><a href="#">Title here</a></span>
    </div>
    <div class="panel callout radius columns small-12 medium-6 large-4">
        <div class="dateNumber" data-bc-date="format:MMM DD">May 08</div>
        <span><a href="#">Title here</a></span>
    </div>
    <div class="panel callout radius columns small-12 medium-6 large-4">
        <div class="dateNumber" data-bc-date="format:MMM DD">Jun 09</div>
        <span><a href="#">Title here</a></span>
    </div>
    <script>
    $(".callout .dateNumber").html(function(){
        return $(this).html().replace(' ', '<br />');
        // Or: return this.innerHTML.replace(' ', '<br />');
    });
    </script>
    </body>
    </html>
    

    Side note: Your replace call will only replace the first space. I think that's probably what you want, but if you wanted to replace all of the spaces, it would be .replace(/ /g, '<br />').