1

I am currently using a Twitch API that receives information about a specific channel then prepends it to the HTML document. The code that prepends the information is used over and over. I was wondering how exactly do you create a function that could avoid repetition and be called throughout the document?

The codepen can be found here: http://codepen.io/sibraza/pen/AXRRvq

Here is the JQuery Code thats gets used repeatedly:

$("#follower-Info").prepend("<div class ='row'>" + "<div class = 'col-md-4'>" + "<img src='" + logo + "'>" + "</div>" + "<div class='col-md-4'>" + name +"</div>"+ "<div class ='col-md-4'>" + status + "</div></div>")

Would something like this work:

function addThis(){

        $("#follower-Info").prepend("<div class ='row'>" + "<div class = 'col-md-4'>" + "<img src='" + logo + "'>" + "</div>" + "<div class='col-md-4'>" + name +"</div>"+ "<div class ='col-md-4'>" + status + "</div></div>")

   }  

And then I can could call addThis() after each $.getJSON request.

1 Answer 1

1

It would work, but you need to pass name, logo and status as parameters to the function. You can also remove the redundant string concatenation:

function addThis(name, logo, status) {
    $("#follower-Info").prepend('<div class="row"><div class="col-md-4"><img src="' + logo + '"></div><div class="col-md-4">' + name + '</div><div class="col-md-4">' + status + '</div></div>');
}  

Then you can call it from within your $.getJSON handler:

addThis('Foo', 'bar.jpg', 'online');
Sign up to request clarification or add additional context in comments.

5 Comments

How come using addThis(logo, status, name) under each handler doesn't work correctly? Those three parameters are declared locally under each handler.
Without seeing your code I would guess they are not in scope of the function.
The code can be seen if you visit the link to the codepen: codepen.io/sibraza/pen/AXRRvq
You define the addThis() function in that code, but you never call it.
Okay, I was able to figure out what I did wrong. The order of the parameters was incorrect.

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.