Creating Functions in JQuery to Avoid Writing the Same Code Again - javascript

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.

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');

Related

How to actually use meta tags to share data through social networks?

So I'm trying to do a website that has multiple images with their own content and allow users to click on a dropdown next to an image and share that image and the content to: Twitter, Facebook, LinkedIn, and Email.
What I've looked into is creating a separate URL for each image with it's content. Then in each page setting it's description, image, etc. in the meta tags. So on the landing page when they click to share it's actually pulling a separate page.
My question is...how do I share meta tag information to Twitter, Facebook, LinkedIn, and Email?
I've tried for Twitter:
<a rel="nofollow" class="share-twitter sd-button share-icon no-text" href="http://twitter.com/share?text=Textgoeshere&url=https://www.landingpage.com/&hashtags=example" target="_blank" title="Click to share on Twitter"><span></span><span class="sharing-screen-reader-text">Click to share on Twitter (Opens in new window)</span></a>
This seems like a lot of text that I would have to then write for each image. Plus it doesn't pull the image, author, etc. Isn't there a way to grab the meta tag information to share to Twitter here?
I mean I have the meta tags present (below) but no idea how to actually use them to share.
<meta name="twitter:card" content="Here's Twitter Card"/>
<meta name="twitter:site" content="#author"/>
<meta name="twitter:domain" content="#author"/>
<meta name="twitter:url" content="http://www.mainpage.com">
<meta name="twitter:title" content="Twitter Title">
<meta name="twitter:description" content="Here is the Twitter Description">
<meta name="twitter:image" content="link to image">
Found the following for Facebook:
https://developers.facebook.com/docs/plugins/share-button#
Found the following for Twitter:
https://publish.twitter.com/#
Okay here is what I'll do for you because I am not sure what answer you are looking for here. We are going to write some javacript that can do this for you.
Here you have your HTML tag. It's important that you give every div the class "twitter-input-card" and you give them an onload function of "updateCards()".
HTML here:
<div class="twitter-input-cards" onload="updateCards(tCard1)"> </div>
Now here is your js....:
//this function creates your object
function twitterCards(twitterCard, twitterAuthor1, twitterAuthor2, twitterURL, twitterTitle, twitterDes, twitterImg) {
//this will be twitter:card
this.twitterCard = twitterCard;
//this will be twitter:site
this.twitterAuthor1 = twitterAuthor1;
//this will be twitter:domain
this.twitterAuthor2 = twitterAuthor2;
//this will be twitter:url
this.twitterURL = twitterURL;
//this will be twitter:title
this.twitterTitle = twitterTitle;
//this will be twitter:description
this.twitterDes = twitterDes;
//this will be twitter:image
this.twitterImg = twitterImg;
}
//this isn't as important but i am not familiar with twitter cards so if there are more meta tags you can define them here.
var tcard = 'twitter:card';
var tsite = 'twitter:site';
var tdomain = 'twitter:domain';
var turl = 'twitter:url';
var ttitle = 'twitter:title';
var tdes = 'twitter:description';
var timg = 'twitter:image';
//this function will update the card with information
function updateCards(selectCard){
cardSelect = selectCard;
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tcard + "' content = '" + twitterCard + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tsite + "' content = '" + twitterAuthor1 + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdomain + "' content = '" + twitterAuthor2 + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + turl + "' content = '" + twitterURL + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + ttitle + "' content = '" + twitterTitle + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdes + "' content = '" + twitterDes + "'/>"
document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + timg + "' content = '" + twitterImg + "'/>"
}
//this is where you define your cards info
var tCard1 = new twitterCards (
//this will be twitter:card
"Here is a new card",
//this will be twitter:site
"here is an author",
//this will be twitter:domain
"here is another aurthor",
//this will be twitter:url
"here is the page",
//this will be twitter:title
"here is the title",
//this will be twitter:description
"here is the description",
//this will be twitter:img
"img.jpg"
)

Dynamically replacing HTML with getJSON by click of button

I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:
$(document).ready(function() {
$("#nav_list a").click(function(evt) {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data) {
$.each(data, function() {
$.each(this, function(key, value) {
$("#main").append(
"<h1>" + value.title + "</h2>" +
"<img src='" + value.image + "'>" +
"<h2>" + value.month + "<br>" + value.speaker + "</h2>" +
"<p>" + value.text + "</p>";
);
}); // inner each
}); // outer each
)}; // end of getJSON
}); // end click
}); // end ready
Notes:
The alert(buildName) is for my own testing.
The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.
Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).
I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:
$.getJSON(buildName, function(data) {
$.each(data, function(key, value) {
$("#main").append(
("#main h1").innerHTML.replace("<h1>" + value.title + "</h2>");
("#main img").innerHTML.replace("<img src='" + value.image + "'>");
("#main h2").innerHTML.replace("<h2>" + value.month + "<br>" + value.speaker + "</h2>");
("#main p").innerHTML.replace("<p>" + value.text + "</p>");
)
}); // endeach
)}; // end of getJSON
What do you guys think? I am absolutely stumped.
Remove the semi-colon at the end inside your .append(). Otherwise, I'm not sure. I wanted to comment this instead of answering but I lack the reputation. With your second attempt, those replace calls shouldn't be made inside the .append(). Good luck!
I think that the problem might be your json path that you construct.
Try using a standard path "../file.json" or "file.json" to check if you have the result you want or if the $.getJSON() is still ignored.
About the other errors: What is your devel. environment?
I also noticed that you have a bracket mismatched in your append function at the title part. So,
"<h1>" + value.title + "</h2>" +
would have to be changed to..
"<h1>" + value.title + "</h1>" +
I have re-created a sample of your site and it all seems to run fine using your code and .json files.
I just needed to modify the code as shown below. In this case, if you have a heading it will also clear the heading in your website.
<!--json retrieve script starts here -->
<script>
$(document).ready(function(){
$(":button").click(function() {
buildName = "../json_files/" + $(this).attr("title") + ".json";
alert(buildName);
//$("#main").empty();
document.getElementById("main").innerHTML = "";
$.getJSON(buildName, function(data){
//$.each(data, function() {
// $.each(data, function(key, value){
$("#main").append(
"<h1>" + data.title + "</h2>" +
"<img src='" + data.image + "'>" +
"<h2>" + data.month + "<br>" + data.speaker + "</h2>" +
"<p>" + data.text +"</p>"
);
// });
//});
});
});
});
</script>
<!--json script end here -->
NOTE: I have swapped the link with button to wire the event for this example.
You can also use multiple file entries in a single .json file in the format shown below:
{
"story1":"/jsonfile1.json",
"story2":"/jsonfile2.json",
"story3":"/jsonfile3.json"
}
which you would then parse with an $.each(data,function(key,value) where value would be the filename to be requested via $.getJSON so you can have multiple entries handled by a single file.
There were a few syntax errors - a parenthesis and curley bracket out of order, misplaced semi-colon, things of the like. The logic was correct.
Thanks all for the replies!

Fancybox iframe does not appear

HTML
<a class="fancybox fancybox.iframe" href="http://www.youtube.com/embed/L9szn1QQfas">Youtube (iframe)</a>
This code line works but I want to add dynamically javascript code.
JS
'<li>' +
'<div class="list-left">' +
'<img src="' + thumb + '">' +
'</div>' +
'<div class="list-right">' +
'<a class="fancybox fancybox.iframe" href="http://www.youtube.com/embed/' + videoID + '"><h3>' + title + '</h3></a>' +
'<small>By <span class="Title">' + channelTitle + '</span> on ' + videoDate + '</small>' +
'<p>' + description + '</p>' +
'</div>' +
'</li>' +
'<div class="clearfix"></div>' +
'';
When I clicked the link, I can't open with fancybox. It's open with new page and console says
Mixed Content: The page at 'https://www.youtube.com/embed/OFMSUI7PAS8'
was loaded over HTTPS, but requested an insecure image
'http://www.youtube.com/favicon.ico'. This content should also be served over HTTPS.
Update
I just used your pen and everything worked fine for me, you forgot to pass type: 'iframe' to fancybox, also you should put your js code in js section in codepen, here is screenshot
And here is the codepen's link: Click me

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

Javascript systax for URL contatenation

I am pulling data from a JSON file into a map and form. I would like to link to new tab with directions to given location. How do I write this?
Working code that opens Yelp link:
<tr><th>Yelp</th><td><a class='url-break' href='" + feature.properties.YelpURL + "' target='_blank'>" + feature.properties.YelpURL + "</a></td></tr>
Not working code for Google Directions using lat long
<tr><th>Directio</th><td><a class='url-break' href='" + https://www.google.com/maps/dir/ + feature.properties.geo_longitude + feature.properties.geo_latitude + "' target='_blank'>" + Get Directions + "</a></td></tr>
The app in progress
quotes are in the wrong place, replace
<a class='url-break' href='" + https://www.google.com/maps/dir/ + feature.properties.geo_longitude + feature.properties.geo_latitude + "' target='_blank'>
with
<a class='url-break' href='https://www.google.com/maps/dir/" + feature.properties.geo_longitude +","+ feature.properties.geo_latitude + "' target='_blank'>

Categories