0

Here I have a code that create a sidebar:

var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>" + '<div class="raty" />' + "</br>";

$(side_bar_html).appendTo('#side_bar').filter('.raty').raty({
    score : place.rating,
    path : 'http://wbotelhos.com/raty/lib/img'
})

How I can create a function from this code to create a sidebar with function ...

So something like that:

function Create_a_sidebar_and_put_it_into_ID#sidebar () {
//for every marker to return html string
 return "<div class='element'>"+place.name+"</br>"+place.rating+"</div>" + etc...

Becouse I have a problem with creating html, I dont know what to append where and I dont have contol over that

Is it possible?

2
  • 1. Put code in function, 2. Invoke function, 3. ???, 4. PROFIT Commented Sep 14, 2013 at 20:57
  • Just do 3. It's that simple. Commented Sep 14, 2013 at 21:00

1 Answer 1

1

If I'm understanding your question correctly, you're asking how you can take your first code block that creates a rating for a certain place, and refactor it so that you can arbitrarily create sidebars for places at will. So that's how I'll approach this answer.

As @Sime Vidas mentioned, you can start by taking the code that creates the sidebar itself and making that a function such as that below. I've modified the function a bit to take the javascript out of the href attribute (which is generally considered a bad practice) and replaced passing an html string into $.fn.init (which I've found steeply degrades performance) with using DOM methods to create elements. You also don't need the <br /> after your a element because divs by default are block elements.

function createSidebar(place) {
    var $sidebarLink = $(document.createElement('a'));
    var $raty = $(document.createElement('div'));

    $sidebarLink.attr('href', '#').text(place.name).click(function(evt) {
        evt.stopPropagation();
        google.maps.events.trigger(gmarkers[parseInt(gmarkers.length - 1, 10)], 'click');
    });
    $raty.addClass('raty').raty({
        score: place.rating,
        path: 'http://wbotelhos.com/raty/lib/img'
    });
    return $([$sidebarLink, $raty]);
}

Now you can do things like

var $sidebar = $('#side_bar');
places.map(createSidebar).forEach(function($sidebarPart) { 
    $sidebar.append($sidebarPart);
});

Sorry if I'm off track with answering your question, but I think this is what you were asking. If not feel free to leave a comment and we can talk about it more!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.