getting jQuery scripts and content through ajax dynamically - javascript

I've got a page which loads a file tree with links to the actual pages and such, with subtrees and everything. But since large folders create huge files, a jQuery script to hide folders would be awesome. There is a problem tho, since the tree is loaded through ajax, and never looks the same, nether does the jQuery. I can generate the jQuery dynamically, but it doesn't load any javascript which is loaded through ajax. Specially not events. (jQuery, onclick)
<ul>
<li><b>www</b> - 5 files, 14 directories, 1877 KB total.
<ul>
<li><b>Admin</b> - 4 files, 3 directories, 44 KB total.
<ul>
<li><b>Editera</b> - 2 files, 16 KB total.
<ul>
<li>gastbok_edit.asp - View Source - 1100 bytes, last modified on 2011-01-17 12:06:43. <b> table names found:</b> Gastbok</li>
<li>Medlem_edit.asp - View Source - 15671 bytes, last modified on 2011-01-17 12:06:44. <b> table names found:</b> Inlogg</li>
</ul>
</li>
<li><b>Radera</b> - 2 files, 2 KB total.
<ul>
<li>gastbok_radera.asp - View Source - 813 bytes, last modified on 2011-01-17 12:06:45. <b> table names found:</b> Gastbok</li>
<li>medlem_radera.asp - View Source - 811 bytes, last modified on 2011-01-17 12:06:45. <b> table names found:</b> Inlogg</li>
</ul>
</li>
<li><b>Uppdatera</b> - 2 files, 2 KB total.
<ul>
sry for the big code, but there is an example of a rendered page and the items in it. I thought that the path variable could be used as a class, therefore giving all items in a path the same class. Thank you for reading my awesome textblock. example: "../../lh10fego/Admin/Radera". Will . and / cause problems? Probably.
Can anyone give me an jQuery code which works in such a way that it will hide/show every item with a class like "myClass" nomatter where they are on the page?
And also a way to activate that code after being added through an ajax-request.
The injected html, including the javascript ends up inside a div in the head of the document.
EDIT: I managed to get almost the needed functionality, but still not through ajax. I used this-keyword and hidden all with the specific class beneath. The problem now is that since the link is inside another link, both the one you clicked and the one at the very top will trigger, hiding everything aswell.
EDIT2:
set fs = CreateObject("Scripting.FileSystemObject")
set folder = fs.GetFolder(path)
currentfolder = path
fname = Replace(folder.path,"/","x")
fname = Replace(fname,".","2")
fname = Replace(fname,":","5") 'removing wierd chars and adding "asd" in middle
fname = Replace(fname,"\","3") 'to avoid multiple hits when searching
fname = Replace(fname,Right(fname,7),"asd" & Right(fname,7))
'Display the target folder and info.
Response.Write("<li onclick=""$(this).find('li." & fname & "').slideToggle();""><b>" & folder.Name & "</b> - " _
& folder.Files.Count & " files, ")
if folder.SubFolders.Count > 0 then
Response.Write(folder.SubFolders.Count & " directories, ")
end if
Response.Write(Round(folder.Size / 1024) & " KB total." _
& vbCrLf)
The problem right now is that since it's applied to nested li-tags whenever i click something, both the one i clicked and the highest li-tag will hide. Also, this test i'm working in right now is without ajax just to get my jQuery sorted.

for a better understanding: You use ajax for load HTML and Javascript code and injecting those into another HTML page. My question to you is: will also simple Javascript, e.g. alert("test");, not work after injection?

after ten days I think I've got a soloution:
<html><head>
<script src="./jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function jqueryAjax(url)
{
$.ajax({
url: ""+url,
cache: false,
dataType: "script",
success: function(html){
$("#content").append(html);
}
});
}
</script>
</head>
<body>
<div id="control" style="border: 1px solid green;">
<p>Ajax with Jquery (1.2.6)</p>
</div>
<div id="content" style="border: 1px solid red; width: 640px; height: 480px; top: 200px"></div>
</body></html>
The bad news is: an error message comes up in the error console and I cannot remove those. But it works...

Related

How to avoid generated duplicade html code in javascript [duplicate]

This question already has an answer here:
How to duplicate a div in JavaScript
(1 answer)
Closed 3 years ago.
Maybe this is a common question in javascript world, but i can't find any usefull keyword for a profitable search. Long story short:
I have html code generated server side, suppose something like this
<div id="container">
<div class="element">
<!-- yadayada -->
</div>
<div class="element">
<!-- yadayada -->
</div>
</div>
and a client script to add new elements without reloading the page
<script>
// do asynchronous server stuff, then add new div from json server output
var string = "<div class=\"element\">\n" +
" <!-- yadayada -->\n" +
"</div>";
$("#container").prepend($(string));
</script>
Well, if the <!-- yadayada --> internal layout is changed in the server scripts, the javascript code must also be changed.
How can I avoid this ? how can I have only one maintainable source for the yadayada layout ?
Clone the first of the elements and prepend it to the container like so:
$('.element:first').clone().prependTo('#container');
As mentioned in the comments, you can 'clone' an item served up by the server.
elem.cloneNode(true)
On a page that I did, I named one element 'master' and then used that to create all new elements as needed (I hid the master with CSS display: none).
As mentioned in other posts you can use .clone() with jquery.
If you do not want to use jQuery, you can use regular javascript:
Excerpt from the W3 Schools site:
// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;
// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);
The above is an example of cloning in regular javascript from W3 Schools site: https://www.w3schools.com/jsref/met_node_clonenode.asp

Display images from Local File in html,css & js website gallery

In my university course/module that covers intermediate HTML and CSS, and basic java-script (thought we haven't gotten there yet): I need to create a website using HTML, CSS and optionally java-script as bonus marks.
I am stuck at the gallery, I want to make a responsive image grid (that I can learn/get from https://www.w3schools.com/howto/howto_css_image_grid_responsive.asp); However I want to have a local folder filled with say 100 images and my website with html/css/js code that doesn't require me to manually hard code each individual image from the folder. In hindsight I want to add and remove images from said folder and have the website's gallery adapting to the added/removed images.
Theoretically I assume that I'll need to read in the folder's contents, into a list/array, then somehow parse them and output the content.
I have found two sources that touches on the idea:
- https://www.html5rocks.com/en/tutorials/file/dndfiles/
- https://github.com/blueimp/JavaScript-Load-Image#meta-data-parsing
I have searched for a few hours and I would think that such a code should exist somewhere, thought I believe my lack of knowledge regarding html, css, js, etc and general terminology is hindering me in my search, thus any advice would be greatly appreciated.
Thank you in advance for your time and effort.
Consider using a shell script from the corresponding directory where source image files are present.
You can simply make a .cmd file with the following code and execute that, it would dynamically generate an html file where you can display images as you wish.
scriptToExecute.cmd
echo ^<!doctype html^>^<head^>^</head^>^<body^> >> index.html
for %%j in (*.JFIF, *.png, *.JPG, *.GIF) do echo ^<img src=^"./%%j^" style="width:176px;height:300px" ^> >> index.html
echo ^</body^>^</html^> >> index.html
index.html
<!doctype html><head></head><body>
<img src="./2.jfif" style="width:176px;height:300px" >
<img src="./3.jfif" style="width:176px;height:300px" >
<img src="./4.jfif" style="width:176px;height:300px" >
<img src="./1.png" style="width:176px;height:300px" >
</body></html>
You can make changes to the shell script to display the images in different elements such as a carousel, etc.
If you want to load images from a folder dynamically (not entering each manually) you can't avoid needing javascript. Adding jQuery into the mix makes it easier not harder. Don't be afraid of using jQuery even if you're only just starting to learn javascript.
To be able to use jQuery, all you need to do is add this:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Essentially what that does is add the $ variable which you'll see in the following code provides a straightforward way to make an ajax call and also to add new img elements to the body element.
To create an element for each image in the folder (assuming it contains only images) should be as simple as the following:
<script type="text/javascript">
var folder = "images"; //TODO: change this to the path to your folder with the images.
$.ajax({
url: folder,
success: function(data) {
$(data).find("a").attr("href", function(i, val) {
$("body").append("<img src='" + folder + '/' + val + "'>");
});
}
});
</script>
Alternately, if you just want to avoid having to type out all the img elements by hand and fill in each src attribute by hand, you can write a bit of javascript that automates that. Using the following script you'll be able to click 'Choose Files' and select all the images in the folder, click 'Open', and then click 'Go' and it will generate the html for all the img elements and display it. You can then copy that html and manually paste it into your real project.
<input id="file" type="file" multiple />
<button onClick="go()">Go</button>
<div id="output"></div>
<script type="text/javascript">
function go() {
const fileInput = document.getElementById('file');
const outputDiv = document.getElementById('output');
let html = '';
for (const file of fileInput.files) {
html += '<img src="images/' + file.name + '" />';
}
outputDiv.textContent = html;
}
</script>
https://codepen.io/rockysims/pen/MPEMOG

Line break before a special character

I use a template webpage, and supplier does not give permission to change most thing in system. But I can reach HTML and CSS of the web, Is it possible to put a line break before "(" character. Is CSS or HTML enough or do I need another coding?
I have HTML like; (Link and Title of that link comming from inline code that i cannot reach or change) Moreover, This HTML code generated automatically from CMS of website, therefore it cannot be update like adding break code before "(". In otherwords, it will not shown in website HTML, it recalled from somewhere else that i cannot update. Therefore I need a coding that recognize "(" char. and put break before it. because text of it not always same length.
<div class="showcaseTitle">
<a href="tour_package_ID_0011.html">
Tour Package (129€) </a>
</div>
I have CSS like;
.showcaseTitle {
height: 32px;
position: relative;
overflow: hidden;
margin: 0 0 5px;
}
It shows on main page of website single line but i need to put the price on second line like below
Tour Package
(129€)
How can i solve this problem ?
Thank you very much
EDIT :
As mentioned in the comments, you can't change the HTML so thx to Harry in the comments here is a JS function that replaces all "(" characters by "<br>(" therefore you will have a line break before the "(" character.
var txt = document.getElementsByClassName('showcaseTitle')[0].innerHTML;
txt = txt.replace(/\(/g, '<br>(');
document.getElementsByClassName('showcaseTitle')[0].innerHTML = txt;
<div class="showcaseTitle">
<a href="tour_package_ID_0011.html">
Tour Package (129€) </a>
</div>
Original answer :
As you can change the HTML markup, the simplest would be to add a line break in the HTML with the line break tag (<br/>) :
<div class="showcaseTitle">
<a href="tour_package_ID_0011.html">
Tour Package
<br/> <!-- this line ! -->
(129€)
</a>
</div>

JavaScript: How should I generate a lot of HTML? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a best practice for generating html with javascript
I want to generate large parts of a website with JavaScript.
The straightforward way is to form one large string containing all the HTML:
'<div>'
+ '<span>some text</span>'
+ '<form>'
+ '<input type="text" />'
...
But this gets quite annoying when one has to write a few hundred lines in this style. And the pain when such code has to be changed later on...
Can you think of an easier way?
Create snippets as templates, put them into an invisible <div>:
<div style="display: none">
<div id="template1">
<h2 class="header_identifyingClass">Hello from template</h2>
</div>
<div id="template2">
<span class="content">Blah blah</span>
</div>
</div>
Then find it,
document.getElementById("template1");
fill it's internal values, e.g. find inside elements by XPath or jQuery and fill them e.g. using element.innerHTML = "Hello from new value", and move or copy it to the visible part of DOM.
Create multiple templates and copy it multiple times to generate many.
Don't forget to change the ID for copies to keep it working.
PS: I think I used this approach in the code of JUnitDiff project. But it's buried in XSLT which serves another purpose.
By far the best way to do this is to use some kind of JavaScript templating system. The reason why this is better than hiding HTML with CSS is that if (for example) someone has CSS disabled, they'll be able to see your templates, which is obviously not ideal.
With a templating system, you can put the templates in a <script> tag, meaning that they're totally hidden from everything except JavaScript.
My favourite is the jQuery templating system, mostly because jQuery is so ubiquitous these days. You can get it from here: http://api.jquery.com/category/plugins/templates/
An example (taken from the jQuery docs):
<ul id="movieList"></ul>
<!-- the template is in this script tag -->
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
<!-- this script will fill out the template with the values you assign -->
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
It's a simple example, but you could put all of the HTML you'd like to generate in the <script>, making it much more flexible (use the same HTML snippet for various jobs, just fill out the gaps), or even use many templates to build up a larger HTML snippet.
Use a dialect of JavaScript such as CoffeeScript. It has heredocs:
'''
<div>
<span>some text</span>
<form>
<input type="text" />
'''
If you need to throw in an occasional expression, you can use interpolations:
"""
<title>#{title}</title>
"""
If it's static content that you're just adding to the page on a javascript event, you could consider simply having it in your main HTML page all along, but style with display:none;.
Then it's just a case of changing it's style to make it appear on the page. Much easier.
Even if it's dynamic, you could use this technique: have the shell HTML content there hidden in your page, and populate the dynamic bits before making it visible.
hope that helps.

Updating the content of a div with javascript

Rather than trying to create tons of different pages on my website, I'm trying to update the content of a single div when different items in the navbar are click to update the maint div content. I tried to find a simple example using Javascript:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<div id="example1div" style="border-style:solid; padding:10px; text-align:center;">
I will be replaced when you click.
</div>
<a href="javascript:ReplaceContentInContainer('example1div', '<img src='2.jpg'>' )">
Click me to replace the content in the container.
</a>
This works just fine when I only try and update text, but when I put an img tag in there, as you can see, it stops working.
Either
1) what is the problem with how I am trying to do it?
or 2) What is a better/easier way to do it?
I'm not stuck on Javascript. jQuery would work too, as long as it is just as simple or easy. I want to create a function that will just let me pass in whatever HTML I want to update and insert it into the div tag and take out the 'old' HTML.
You just have some escaping issues:
ReplaceContentInContainer('example1div', '<img src='2.jpg'>')
^ ^
The inner ' need to be escaped, otherwise the JS engine will see ReplaceContentInContainer('example1div', '<img src=' plus some syntax errors resulting from the subsequent 2.jpg'>'). Change the call to (tip of the hat to cHao' answer concerning escaping the < and > in the HTML):
ReplaceContentInContainer('example1div', '<img src=\'2.jpg\'>')
A simple way to do this with jQuery would be to add an ID to your link (say, "idOfA"), then use the html() function (this is more cross-platform than using innerHTML):
<script type="text/javascript">
$('#idOfA').click(function() {
$('#example1div').html('<img src="2.jpg">');
});
</script>
First of all, don't put complex JavaScript code in href attributes. It's hard to read or to maintain. Use the <script> tag or put your JavaScript code in a separate file altogether.
Second, use jQuery. JavaScript is a strange beast: the principles underlying its patterns were not designed with modern-day web development in mind. jQuery gives you lots of power without miring you in JavaScript's oddities.
Third, if your goal is to avoid having to endlessly duplicate the same basic structure for all (or many) of your pages, consider using a templating system. Templating systems allow you to plug in specific content into scaffolds containing the common elements of your site. If it sounds complicated, it's because I haven't explained it well. Google it and you'll find lots of great resources.
Relying on JavaScript for navigation means your site won't be indexed properly by search engines and will be completely unusable to someone with JavaScript turned off. It is increasingly common--and acceptable--to rely on JavaScript for basic functionality. But your site should, at minimum, provide discrete pages with sensible and durable URLs.
Now, all that said, let's get to your question. Here's one way of implementing it in jQuery. It's not the snazziest, tightest implementation, but I tried to make something very readable:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Example</title>
<style type="text/css" media="all">
/* all content divs should be hidden initially */
.content {
display: none;
}
/* make the navigation bar stand out a little */
#nav {
background: yellow;
padding: 10px;
}
</style>
</head>
<body>
<!-- navigation bar -->
<span id="nav">
about me |
copyright notice |
a story
</span>
<!-- content divs -->
<div class="content" id="about_me">
<p>I'm a <strong>web developer</strong>!</p>
</div>
<div class="content" id="copyright">
<p>This site is in the public domain.</p>
<p>You can do whatever you want with it!</p>
</div>
<div class="content" id="my_story">
<p>Once upon a time...</p>
</div>
<!-- jquery code -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
// Wait for the document to load
$(document).ready(function() {
// When one of our nav links is clicked on,
$('#nav a').click(function(e) {
div_to_activate = $(this).attr('href'); // Store its target
$('.content:visible').hide(); // Hide any visible div with the class "content"
$(div_to_activate).show(); // Show the target div
});
});
</script>
</body>
</html>
Ok, hope this helps! If jQuery looks attractive, consider starting with this tutorial.
Your main problem with your example (besides that innerHTML is not always supported) is that < and > can easily break HTML if they're not escaped. Use < and > instead. (Don't worry, they'll be decoded before the JS sees them.) You can use the same trick with quotes (use " instead of " to get around quote issues).

Categories

Resources