SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    May 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question want to point javascript to ID?

    hi im new to javascrtipt and donīt know the terms so cant find out what to search for

    i have code that truncate the text of my links
    so <a href="myfruitandvegetable.com">Fruit and vegetables</a>
    result without code Fruit and vegetables
    and with code Fruit and...

    here is code i found on the net.
    Code:
    <script type="text/javascript">
    var oElement = document.getElementById("test");
    $('a').text(function(index, oldText) {
      return oldText.length > 9 ? oldText.substring(0, 9) + '...' : oldText;
    });
    </script>
    so far so good.
    i also have other link on same page
    <a href="myhomepage.com">Copyright 2012 myhomepage.com</a>
    so when the script is on as you already has guessed.
    the result would be Copyright...
    what it should not do.

    so i was thinking
    what if i gave the 2 links some id like this
    <a id="truncateon" href="myfruitandvegetable.com">Fruit and vegetables</a>
    <a "truncateoff" href="myhomepage.com">Copyright 2012 myhomepage.com</a>

    so code only truncated link if it has the id=truncateon"
    i think in the javascript line 2
    $('a').text(function(index, oldText) {
    is the one that find the<a tag with the $('a') code.
    but dont know how or if its possible to add the id="truncateon" to it.

    hope it makes sense.
    mu best regards dahlsvarehus

  2. #2
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    An ID must be unique on the page, so you cannot have two elements with the same ID.
    Instead of an ID you could use a class, or perhaps data attribute. I don't know much about using data attributes in selectors so we'll go with a class

    HTML Code:
    <a href="myfruitandvegetable.com" class="truncate">Fruit and vegetables</a>
    <a href="myhomepage.com">Copyright 2012 myhomepage.com</a>
    Code JavaScript:
    <script type="text/javascript">
    $('a.truncate').text(function(index, oldText) {
      return oldText.length > 9 ? oldText.substring(0, 9) + '...' : oldText;
    });
    </script>

    There's no need to mark both the links to truncate and the links to not truncate. One is the inverse of the other.
    mikehealy.com.au
    diigital.com art, design . Latest Work — Saturday Morning

  3. #3
    SitePoint Member
    Join Date
    May 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thank you cranial-bore
    Perfect!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •