Kappaluppa
Kappaluppa

Reputation: 333

use a href as a var in a jquery function

I have a function that requires some vars being appended to a div. One of the vars is an a href link with onclick. How do I format the link to work in the var within the function? The below is not working.

What the whole purpose of this is is to

I've taken two snippets of code

and am trying to mash them together to come up with what I need. Each snippet works on its own.

This is the code as I have it now:

<script type="text/javascript">
    function showStuff(id) {
        document.getElementById(id).style.display = 'block';
    }
    function hideStuff(id) {
        document.getElementById(id).style.display = 'none';
    }
$(function() {
    var limit = 200;
    var chars = $("#myDiv").text(); 
    if (chars.length > limit) {
        var visiblePart = $("<div> "+ chars.substr(0, limit-1) + "</div>");
        var readMore = $(<a href="#" onclick="showStuff('answer1'); return false;">open</a>);      
        var hiddenPart = $("<span id='answer1' style='display: none;'> " + chars.substr(limit-1)  + "</span>");
        var readLess = $(<a href=\"#\" onclick=\"hideStuff('answer1'); return false;\">close</a>); 
        });

        $("#myDiv").empty()
            .append(visiblePart)
            .append(readMore)
            .append(hiddenPart)
            .append(readLess);
    }
});

Upvotes: 1

Views: 290

Answers (2)

Dave L.
Dave L.

Reputation: 9801

Modified Felix's version above so both links weren't showing at the same time:

http://jsfiddle.net/cXw5D/4/

EDIT:

Cleaned up syntax one last time:

http://jsfiddle.net/cXw5D/5/

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816700

If you use jQuery, then use it consistently. The biggest error you have above is that the HTML is not inside strings, hence you will get a syntax error in JavaScript.

Here is a slightly improved version:

$(function() {
    var limit = 200;
    var chars = $('#myDiv').text(); 
    if (chars.length > limit) {
        var visiblePart = $('<div />').text(chars.substr(0, limit-1));
        var readMore = $('<a />', {
             href: '#',
             click: function() {
                 hiddenPart.show();
                 return false;
             },
             text: 'open'
        });      
        var hiddenPart = $('<span />', {text: chars.substr(limit-1)}).hide();
        var readLess = $('<a />', {
             href: '#',
             click: function() {
                 hiddenPart.hide();
                 return false;
             },
             text: 'close'
        });  

        $('#myDiv').empty()
            .append(visiblePart)
            .append(readMore)
            .append(hiddenPart)
            .append(readLess);
    }
});

It is still far from perfect but might give you a start: http://jsfiddle.net/fkling/cXw5D/

Upvotes: 3

Related Questions