Home Ask Login Register

Developers Planet

Your answer is one click away!

Baldráni February 2016

Calling a function inside an other function in Js

I do not understand what am I doing wrong in it can someone explain me ?


The idea is to have a simple function of resuming text. If the text is too long put a "..." and on click display the full length. And then add a span at the end to hide it again.

So #infoCountry is a <p>element over than 200 characters.

if(document.getElementById("infoCountry").innerHTML.length > 200){
    function test(){
        var fullInfo = document.getElementById("infoCountry").innerHTML;
        var semiInfo = fullInfo.substring(0,200) + '<span id="plusInfo">...</span>';
        document.getElementById("infoCountry").innerHTML = semiInfo; 

        var voirPlus = document.getElementById("plusInfo");
        voirPlus.addEventListener("click", function(){
            document.getElementById("infoCountry").innerHTML = fullInfo +'<span id="moinsInfo">&nbsp; Cacher</span>'; //Affiche tout et "Cacher"
            var voirMoins = document.getElementById("moinsInfo"); 
            voirMoins.addEventListener("click", test()); // HERE IS THE BUG ?


It work until I try to recall it. But the console stay empty. I don't understand where is the miss understanding there :/


naomik February 2016

Something like this could work. It doesn't require a <span> like your question suggests

function showExcerpt(elem) {
  var text = elem.textContent;
  if (text.length <= 200) return;
  var link = document.createElement('a');
  link.onclick = function(event) {
    elem.textContent = text;
  link.textContent = '...';
  elem.textContent = text.substring(0,200);

Meatloaf tongue hamburger shank bresaola pork ribeye jerky sirloin bacon meatball venison. Swine andouille turkey, porchetta pork drumstick cupim sirloin chuck meatloaf hamburger ball tip sausage frankfurter. Ball tip hamburger beef ribs shankle. Pig spare ribs sausage meatball beef tenderloin tail bresaola pork loin. Tenderloin jowl pork chop, brisket frankfurter pork venison filet mignon. Ground round flank shank, tri-tip sausage beef ribs pig tenderloin filet mignon sirloin pork leberkas. Drumstick shoulder salami prosciutto andouille pork chop spare ribs turducken hamburger pork belly ham meatloaf rump alcatra.</p>

<p>Chicken t-bone pig flank. Strip steak hamburger t-bone tri-tip</p>

Warning: If your <p> contains HTML elements within, such as <b>some words</b> it's possible that the 200 chars could split a tag in half, resulting in "this is some text ... <b>some wo". This will cause an additional issue for you.

Post Status

Asked in February 2016
Viewed 3,190 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life