Split javascript file into multiple files - javascript

i am not familiar with javascript/jquery, that's why my question:
I want to split existing javascript file to make code more readable.
I have multiple text blocks, which i want to put in separate file/files.
What is the best way to realise it?
if (facet === "FACET_NAME") {
$(this.target).append(
$('<span> </span><a class="click" onclick="show_hidePopUpWindow(\'foo\');"
onmouseover="" style="cursor: pointer;"> ' + info_button + "</a>" +
"" + '<div class="menu" id="foo" style="display:none">
<a onclick="show_hidePopUpWindow(\'foo\');">' +close_button +"</a><b> TEXT </b>\n"
+"<br><b>CONTENT:</b> Fulltexts of all articles from the inception ...\n" +
"<br><b>NOTE:</b> To see the image-PDF of the issue you will have go to the database ... \n</div>"
));}

You can insert your js file into another file with the line:
<script src="/path/to/script.js"></script>

Related

How to put linebreaks on dynamically generated javascript code

Working on ASP.net website. In my webpage I'm dynamically writing some javascript in the code-behind code. How can I put linebreaks at certain points so that if I do a 'view source' of the page it is more readable? Right now all the dynamic js code is one one line.
I've tried appending <BR/> but that doesn't seem to work.
Thanks!
<br /> is html element which will not help you at this point. you can use Environment.NewLine to add these line-breaks: example code will be like the following:
StringBuilder strBuilderJS = new StringBuilder();
strBuilderJS.Append("<script language='javascript' type='text/javascript'>" + Environment.NewLine +
"$(WireEvents_" + this.ID + ");" + Environment.NewLine +
"function WireEvents_" + this.ID + "(){" + Environment.NewLine +
" alert('stuff');");
strBuilderJS.Append(Environment.NewLine + "}</script>");
If you're using Response.Write(), you can use \r\n to add a newline in your HTML output.
Example:
Response.Write("<div>\r\nThis is my text.\r\n</div>"
This will appear in the HTML as:
<div>
This is my text.
</div>

how to dynamically action an angular ng-include command

Is it possible to dynamically add an ng-include element to a HTML page and have it actioned?
I have a Drag N Drop application where you can drag an element onto the page and in the drop zone the element is replaced with a more detailed element. For examples you drag a box that says Calendar and when it is dropped a calendar is presented. To be clear a new Element is created and added to the DOM, it does not exist before the drop.
When the element is dropped, I'm hoping that I can replace it with a chunk of HTML that looks like below. Instead of having the markup defined in a string like it is at the moment which is not very nice:
<div class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-remove'></span>
WIDGET NAME
<spanclass='glyphicon glyphicon-cog'></span>
</h3>
</div>
<div class='widgetContainer' ng-include="'widgets/widget.html'"></div>
</div>
When the above HTML is inserted into the page the referenced HTML file is not included.
What I would like to happen is a HTML file is loaded containing the widget markup and included at the appropriate position.
I'm new to Angular so I don't know if this is because:
dynamically adding ng-include isn't supported
whether I need to do something with the controller to handle this logic
should I be using the tag instead of the attribute?
it just isn't possible.
Please provide examples with solutions, as I said I'm new to Angular.
Thanks
UPDATE
The code used to created the HTML that I want to dynamically add to the page looks like this
$("#template").append(
" \
<div class='panel panel-default'>\
<div class='panel-heading'>\
<h3 class='panel-title'>\
<span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeElement(this)'></span>\
" + widgetDetail['serviceName'] + "\
<span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
</h3>\
</div>\
<div class='markupContainer' ng-include=\"'widgets/" + id +".html'\"></div>\
</div>\
"
);
I've uploaded the complete code to GitHub. The drag and drop aspects are being handled currently by HTML5 javascript, which can be seen in the file /public/javascripts/js_dragndrop.js. The new widget being added to the page (the code above) is in /public/javascripts/jq_dragndrop.js
I'm in the prototyping phase trying to work out the DragNDrop elements so don't expect high quality code :)
I found a way of achieving what I wanted by moving the HTML5 drop and drop code into AngularJS directives and then (using this [ Compile dynamic template from outside of angular ] as a guide) got the html templates being loaded where I wanted them.
The main code change looks like this:
angular.element(document).injector().invoke(function ($compile) {
var widgetDetail = widgets[e.dataTransfer.getData('Text')];
var obj = $("#template");
var scope = obj.scope();
obj.append(
"<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>\
<span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeWidget(this)'></span>\
" + widgetDetail['serviceName'] + "\
<span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
</h3></div><div class='markupContainer' ng-include=\"'widgets/" + widgetDetail['serviceId'] + ".html'\"></div>\
"
);
$compile(obj.contents())(scope);
scope.$digest();
});
You can find the full code in the Git Project /public/controllers/template.js if you are interested.

Calling and json file and displaying it on html

I want to display images from my json file on a html page and organise them into rows of 3 or 4. Below is an example of the layout I want my page but this is hard coded,I have included images because I have having difficulty pasting the code (I can put this on fiddler) don't mind some of the word under the pictures some p tags needed taken out:
HTML:
<div id="container">
<div class="row">
<div class="product-container"> </div>
<div class="col-sm-4">
<img src="Image/iphone5.jpg" alt="StrappyMeshInsertDress" style="width:200px;height:250px">
<p><span> class="bold">Iphone5s</span><br />
</div>
Here is a snip from my json file:
json data
I am using this script to call the data although it has not been calling the json file:
the script
I have positioned the images when hard coding like this:
I have been at this for over a day and cannot get it to work, If anyone has any ideas on how to get this to work I would be very grateful.
Kind regards!
Please make sure that you are appending JSON data dynamically so please remove the HTML content, or only make a parent container who will hold all this Output data.Make a JSON file with the name 'iproducts.json' on the same path.
$.getJSON('iproducts.json',function(products){
var output=" <table border='1'><thead><th>Product_id</th><th>Info</th><th>Imgpath</th><th>Price</th><tbody>";
$.each(products.appleitems,function(index,value){
output+="<tr><td>" + value.Product_id + "</td><td></td></td><td>" + value.Information+"</td><td>"+"<img src ='images/" + value.Imgpath + ".jpg' alt='applepro' id='appleinf'" + value.Price +"</td><td>"
});
output+="</tbody></table>";
console.log("output =" + output);

Removing HTML from a jQuery .append()

I have a Parse.com backend and am rendering its data, ultimately, with a jQuery append, like this:
$(".albums").append(
"<div class='col-xs-6 col-6 col-sm-3 col-lg-3'><div class='flip animated fadeInDown' style='-webkit-animation-delay:" + i * 0.1 + "s'><div class='card'><div class='album front' style='background-image:url(" + bigImg + ")'><img class='artwork' src='" + artwork + "' alt='" + collectionName + "' /></div><div class='album back' style='background-image:url(" + back + ")'><img class='artwork' src='" + back + "' alt='" + collectionName + "' /></div></div></div></div>");
It's a for loop hence the need for the various HTML elements and their classes. I know it's an appalling, shameful way to do it (and I believe it's causing a memory leak).
My questions are: How can I remove as much of the HTML from this append statement as possible? Should I be using a templating language?
If you think you might want to use a templating language you can start by building your own, super simple, template.
Simply replace
"some string stuff " + someValue + " some more stuff"
// instead
var myTemplate = "some string stuff {someValue} some more stuff";
// now render
myTemplate.replace('{someValue}', someValue);
It's easy to go further, and wrap this in a function to "render" that takes an object as an argument and iterates over keys. Done carefully this will provide you a subset of the functionality provided by "off-the-shelf" templating libraries so you can always cut-over later.
This will allow you to predefine your "template" and render using the data input provided. The next question is where do you want to define your template. Generally you would relocate it to a separate free-standing file that the designers would have access to, perhaps in a "templates" directory. But then you have to load it.
If you have lots of templates, some libraries would allow you to pack them together in one file, load the file, then ask the library for a specific template by name. Your designers would then control this file and the CSS that goes with it. If you have a lot of this, then the architectural overhead starts to make sense.
Whether you want to go down that road really depends on your specific circumstances and the structure of your project team.
I like Handlebar for this sort of thing.
This would be the template
<script id="albumsTemplate" type="text/x-handlebars-template">
<div class='col-xs-6 col-6 col-sm-3 col-lg-3'>
<div class='flip animated fadeInDown' style='-webkit-animation-delay:{{delay}}s'>
<div class='card'>
<div class='album front' style='background-image:url({{bigImg}})'>
<img class='artwork' src='" + artwork + "' alt='{{collectionName}}' />
</div>
<div class='album back' style='background-image:url({{back}})'>
<img class='artwork' src='" + back + "' alt='{{collectionName}}' />
</div>
</div>
</div>
</div>
</script>
And then you would use it like this:
var source = $("#albumsTemplate").html();
var template = Handlebars.compile(source);
var html = template({delay:i*0.1,
bigImg:bigImg,
collectionName:collectionName,
back:back});
$(".albums").append(html)
Adding html() to the call should do it. That'll return the html inside of .albums. To get everything including .albums you do $('.albums').append(...).parent().html().

Javascript returning variable outside of intended markup

Ok, simple thing I'm overlooking here. The following javascript is returning the title variable outside the anchor tag rather than inside of it (as the code looks to be written to me).
I know I'm missing something obvious, like a method to return the variable as a string or something similar but I'm not sure what's going on.
Help?
EDIT: My mistake, it's "view site" which is being returned outside the <a> tag
// Convert logo img alt tags into div.caption 's
$(".imgs_wrap img").each(function(i, ele) {
var title = $(ele).attr('title');
var description = $(ele).attr('alt');
$(this).parent().prepend('<div class="caption popup"><p> ' +description + ' <a target="_blank" class="view_site" href="http://'+title+'" />View Site</a></div></p>');
});
You're mistakenly using the self-closing tag syntax when rendering the <a>:
bad line:
$(this).parent().prepend('<div class="caption popup"><p> ' +description + ' <a target="_blank" class="view_site" href="http://'+title+'" />View Site</a></div></p>');
change to:
$(this).parent().prepend('<div class="caption popup"><p> ' +description + ' <a target="_blank" class="view_site" href="http://'+title+'" >View Site</a></div></p>');

Categories