Reuse javascript code on client side (node.js, express) - javascript

I'm still new to Node.js, but I'll try to explain my problem as good as I can.
So I'm working on a movie site to practice my node.js/express skills a bit and I use the following elements (img) on basically every page of my website:
Header with stats and search input and a navigation bar (will be reused on every page)
The follow JS-code are two examples of actions on the client side that I use to navigate to other web pages, this then activates GET on the client side.
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
I want this to be the same code on every page. I could type the same code every time, but that would be a waste of time.For HTML and CSS I am able to use templates (HTML) or import other CSS files to save time. Is there something similar for JS on the client side?

Put that code in a file, for example "navigator.js" and then load it in your html header in every page you want to use it
navigator.js:
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
index.html
<script src="navigator.js"></script>
Finally i suggest you to assign an id to your button, for example "searchButton" instead only "button"
Hope this helps

Related

JSLink to Hyperlink Column in SharePoint List

I have an external list in SharePoint that includes a URL column. The URL column is a calculated field in SQL server, so the entire URL is already there. I need this field to hyperlink and I have been trying to use JSLink to do so. What would the JavaScript for that look like?
For example, if my fields were...
First Name | Last Name | Profile URL
How would I get the URL in the Profile URL field to hyperlink?
I have been looking for solutions all morning without any luck. I am not familiar with JavaScript, so the code I am using is pieced together from posts I have been reading. I have made sure the my JSLink address is correct.
~site/SiteAssets/myCode.js
I have tried different variations of code. My latest is this:
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"Profile_X0020_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema["Profile_X0020_URL"]];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();
After applying my JSLink to my web part I reload the page and nothing happens. No errors but no links.
I'm also not sure how to reference the column. In SQL Server it is PROFILE_URL, but in the SharePoint list header it is Profile URL.
Modify the code as below to check if it works.
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"PROFILE_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();

How to get Request.ApplicationPath in jQuery

On my razor view, I am wanting to put all of my jQuery into a separate JS file and then reference that file on the view with #Scripts.Render.
On my view, I have a section jQuery that looks like this:
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var submissionUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
submissionUrl = settings.baseUri + "/api/apiControllerName/apiControllerMethodName/";
} else {
submissionUrl = settings.baseUri + "api/apiControllerName/apiControllerMethodName/";
}
This section of code allows me to test submitting forms with api on both my localhost and live on the server without me having to change the url.
If I am testing on my localhost, then #Request.ApplicationPath == /, but if I test on my server then #Request.ApplicationPath == /ProjectNameOnServer.
I was wondering how I could achieve getting these same values but without the use of Razor, and instead only with jQuery.
I have tried:
var settings = {};
settings.baseUri = window.location.protocol + "//" + window.location.host;
but then settings.baseUri == http://localhost:xxxxx. I just need exactly what #Request.ApplicationPath is giving me.
Use location.host to conditionally create relative path
settings.baseUri = location.host.includes('localhost') ? '/' : '/ProjectNameOnServer';

window.location.replace() not working [duplicate]

I want to navigate to a URL on my site. This is what I have:
var TheDemoURL = window.location.host;
if (SomeCondition1) { TheDemoURL = TheDemoURL + '/fr/demo'; }
if (SomeCondition2) { TheDemoURL = TheDemoURL + '/de/demo'; }
...
window.location.replace(TheDemoURL);
Initially, in the variable watch, I have TheDemoURL: "localhost:49173" and when I alert the final TheDemoURL is looks a good URL but in reality nothing happens.
Why is this not working?
Ok, for those who come here, the solution was to add this:
var TheDemoURL = window.location.protocol + '//' + window.location.host;
Not sure if this is specific to asp.net but it made it work.
Try using
self.location = TheDemoURL;
This will take into account iframes and other weirdness.

twitter sharing button bit.ly integration on a static website

I am trying to integrate bit.ly on my website in JS to short my url. All my url are too long, what will be the most straight foward way to use the bit.ly restful api for sharing button on a static website in HTML/javascript.
The result I want to get is when my user click share on my website the url is automatically shortened by bit.ly
here is the code I am currently using to share my pages dynamically on twitter:
<script type="text/javascript" charset="utf-8" src="http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
function tweetCurrentPage()
{ window.open("https://twitter.com/share?url=" + escape(window.location.href) + "&text=" + document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600'); return false; }
var TweetThisLink = {
shorten : function(e) {
e.preventDefault();
var url = this.href.substr(this.href.indexOf('http:',5))
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response : function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "I am reading documentation of"
document.location = "http://twitter.com/share?url=" + encodeURIComponent(tweet_text + ' ' + bitly_link);
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
tweet this link
Not sure if this is on purposefully obfuscated for the sake of the question, but
In your script tag the src is:
"http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY".
LOGINID & apiKey are placeholders are in-place. You need to replace them with the appropriate keys you should receive from bitly.
if this is on purpose for the sake of the question please ignore this answer.
don't know why but my function "tweetCurrentPage()" for dynamic url won't work it's giving me a respond INVALID_URI from bit.ly, but if I hard code the href value like this twitter.com/share?url=+exemple.com"; it's working...

Change the folder name of URL with a text link?

I have a site with two languages contents, both have the same file names but are stored in different folders: /EN/ and /ZH/.
I would like to have a text link which allow it to be clicked and change the folder name of the URL.
like by clicking the text link "ZH", it will change the URL as:
from => "http://example.com/GroupA/EN/index.asp"
to => /ZH/index.asp"
I have search around and found a script as below:
Script:
$(function() {
$(".flag").click(function(e) {
e.preventDefault();
var to = $(this).attr("href").substring(1); //removes the hash value # (#en will become 'en')
var from = jQuery.url.segment(-2);
var url = from.replace('/' + from + '/', '/' + to + '/');
document.location = url;
});
});
Body:
<a id="flags" href="#en" class="flag">English</a>
However, when I tried the script above, it only add "#en" to the end of my URL, like
http://example.com/GroupA/EN/index.asp#en
$(function() {
$(".flag").click(function(e) {
e.preventDefault();
var to = $(this).attr("href").substring(1); //removes the hash value # (#en will become 'en')
var url = window.location.hostname + "/GroupA/"+to.toUpperCase()+"/index.asp"
window.location.assign(url);
});
});

Categories

Resources