How to link to a file one level above the current one - javascript

In CSS I know that I can reference/link to another file using either of the following:
photo.jpg or ./photo.jpg for a file in the same location as the one I am working in, and photo-folder/images/photo.jpg or ./photo-folder/images/photo.jpg to link a file in one or more directories below/inside the parent directory of the one I am working in.
I also know the same idea applies in HTML like ./[href] or [href].
But I am wondering, let's say the positions of the files in my example are reversed, that is, I want to link to a photo in a directory which is the direct/indirect parent of the file I'm working in. How would I call that file without using the full drive address such as C:/Users/Username/Code/etc/photo.jpg, while my working file is C:/Users/Username/Code/etc/code/file.css...
How is it done in these languages: HTML, CSS, JS, Python? (You are welcome to answer for other languages, I might need it later! :D)
Side question: is there any technical difference between ./file and file, and would it be preferable to stick to one format over the other (e.g. to prevent problems, for readability, etc)? Though I have never run into any problems using either, or even combining both in the same project...

To get to parent directory use ../, this is "per directory", so if you need access several levels up, you'd need use: ../../../ (for 3 levels)
As of using ./ for current directory - it's redundant
As far as I know this is pretty much applies to all languages, however in HTML/CSS there is another relative path that can be used to get to the root of the domain: / (no dots)
so for example if you open https://example/some/long/path/file.html and need access to file at http://example/file.jpg you simply put as relative path: /file.jpg

Related

Load Random Image From Directory on Page Load Without a Listed Array of File Names

I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).
I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.
Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)
Are all file names image1 image2 image3 etc? Then you could try to generate a random number, create a new img element and have it's source pointing to image+randomnumber.jpg and append it to the DOM
One of the main problems your facing here is about your thinking when it comes to how content is delivered, in a standalone static website you do not have access to the file system. This means that if we want to query things outside of the browsers context we are not allowed, obviously without being able to access directories we can not generate a list of file names which can be loaded.
If your wondering why we can't access the file system directly from say the JavaScript it's because of the sandbox that most modern browsers live in, otherwise people could attack your native directories from the front end languages. Your question is interesting as electron removes this sandboxing in a sophisticated esk manner, which is necessary as it's used for building desktop apps with chromium.
These days the most obvious solution would be to use some form of back end language and to create a web server that has direct access to the native directories around it. Node, PhP, GoLang and many other populatr backend languages can parse a directory of files and then interpolate those into the frontend code which is the most common method.
The other popular method at the moment is to create API's which is just a fancy web server with a queryable end point that then executes code against our web server and provides back a list of such items. You could then for instance take the items and then print those out using javascript.
Reference directories method in php:
http://php.net/manual/en/ref.dir.php
List contents of directory in nodejs:
https://code-maven.com/list-content-of-directory-with-nodejs
The best place to really start with the easiest route to understand more would be to start a backend language in either node or php, with php being the simpler of the two.
https://www.w3schools.com/php/
First you need to get your file list from server side. then you can use a code like following:
var imageList = //your image list as an array of urls;
var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
var imageToLoad = new Image();
imageToLoad.addEventListener("load", function(){
console.log( "image is loading" );
$('#my-container').append(this); //in this case this will return image dom
});
imageToLoad.src = imageList[imageNumber];
this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'
So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:
Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.
Code Block:
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo "<img src='$randomImage'>";
?>
Thank you #bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)
Thanks again to everyone that helped me out!

How can I: Replace all instances of an old 'base' href on archived website with a new one for quick changeover?

This problem has come up before for me. I had to manually (or using search/replace in an HTML editor) replace all instances of EXAMPLE.COM with MYTESTSERVER.COM/EXAMPLE for sake of links/images not being broken (This includes any values for HREF or SRC properties--especially these types, actually).
The site was made in 2012... it does include template files (WordPress theme I developed painstakingly over the course of 5-6 months). The template files aren't really what I'm concerned with... it's the countless references to the old domain that was used within the "post" files...
This was an "Online Literary Journal", so there's enough supporting graphics spread throughout the individual posts' code to make me want to find a script to stick in the header.php or footer.php which will change this all over for me on each browser load, without me having to alter the code much (at least for the time being while this is still an "archived" client site)...
THANKS!
NOTE: I am NOT actually using any kind of <BASE> coding... as in building links through the structure of the site's code based on a single instance of a base href. This site was one of my first WordPress projects, and furthermore one of my first "dynamic-like" sites... so I also did not utilize WordPress' php function of bloginfo()... WISH I HAD NOW LOOKING BACK!
**also now i realize that using PHP code within posts isn't the easiest thing to do... nor was it then, so the links were coded as static.
Download the site to your local machine
Use Sublime Text:
Press cmd + shift + F / ctrl + shift + F (Win)
Select the ... symbol & Choose add folder
Choose your folder and do your 'global' search and replace.
Note: Might be a good time to entertain using partials and setting up light static site generator to make this work easier going forward

Make source maps refer to original files on remote machine

Using Google Closure Compiler to minify a bunch of javascripts. Now I'd like to also add source maps to those to debug out in the wild.
Thing is, I want to keep the original (and preferrably also the map files) on a completely different place, like another server. I've been looking for a solution to this, and found out about the sourceRoot parameter. But it seems as it's not supported?
Also found this --source_map_location_mapping parameter, but no documentation whatsoever. Seems as it wants a pipe-delimited argument (filesystem-path|webserver-path). Tried a couple of different approaches to this, like local filename|remote url but without prevail. That just gives me No such file or directory and java.lang.ArrayIndexOutOfBoundsException.
Has anyone succeeded to place the minified/mapped source files on a remote machine?
Or does anyone know of any documentation for --source_map_location_mapping?
Luckily Google Closure Compiler's source code is available publicly
https://gist.github.com/lydonchandra/b97b38e3ff56ba8e0ba5
REM --source_map_location_mapping is case SENSITIVE !
REM need extra escaped double quote --source_map_location_mapping="\"C:/tools/closure/^|httpsa://bla/\"" as per http://stackoverflow.com/a/29542669
java -jar compiler.jar --compilation_level=SIMPLE_OPTIMIZATIONS --create_source_map=C:\tools\closure\latest\maplayer.js.map --output_wrapper "%output%//# sourceMappingURL=maplayer.js.map" --js=C:\tools\closure\mapslayer.js --js_output_file=maplayer.min.js --source_map_location_mapping="\"C:/tools/closure/^|httpsa://bla/\""
The flag should be formatted like so:
--source_map_location_mapping=foo/|http://bar
The flag should be repeated if you need multiple locations:
--source_map_location_mapping=foo/|http://bar --source_map_location_mapping=xxx/|http://yyy
But what I expect that you are running into is that the "|" might be interpreted by your command shell. For example:
echo --source_map_location_mapping=foo/|http://bar
-bash: http://bar: No such file or directory
(The choice to use "|" was unfortunate). Make sure it is escaped appropriately. like:
--source_map_location_mapping="foo/|http://bar"
I submitted a pull request to report an error for badly formatted flag values:
https://github.com/google/closure-compiler/pull/620
which will at least you know that your flag value is incorrect (so you won't see the out of bounds exception).
John is correct functionality-wise, but I think I can clear it up a bit (as this was super confusing for me to get working).
I suspect many people have the same issue as I:
source map urls are generated relative to your current directory
they don't necessarily match up to relative urls on your website/server
Even if they did match up directly, the strangely-defined pseudo-spec found here means that Chrome/Firefox are going to try to load your paths relative to your sourcemap. i.e. the browser loads /assets/sourcemaps/main.map, sees assets/js/main.js, and loads /assets/sourcemap/assets/js/main.js (yay). (Or it might be relative to the original js file actually, I just happened to have them in the same directory).
Let's use the above example. Say we have assets/js/main.js in our sourcemap, and want to make sure that loads mywebsite.com/assets/js/main.js. To do this, you'd pass the option:
--source_map_location_mapping="assets|/assets"
Like John mentioned, quotes are important, and repeat the arg multiple times for multiple options. The prefixed / will let Firefox/Chrome know you want it relative to your website root. (If you're doing this in something like grunt-closure-tools you'll need to escape more:
config:{
source_map_location_mapping:"\"assets|/assets\"",
}
This way, we can essentially map any given sourcemap path to any given website path. It's not really a perfect replacement for some sort of closure source root, but it does let you map each section of your sources individually to their own roots, so it's not that bad a compromise, and does give some additional flexibility (i.e. you could specify some cdn paths for some of your assets but not for other).
An additional thing you might find helpful, you can automatically add the sourceMappingURL via an output_wrapper. (Though, if you want the ability to debug in production, you should probably prefer some ability to make the server return X-Sourcemap: blah.js.map headers instead, inaccessible by the public)
--output_wrapper="(function(){%output%}).call(this); //# sourceMappingURL=/assets/js/my_main_file.js.map"

tracking a javascript found in pagesource

ive tried everything i cud to figure this out, but i cannot track a piece of javascript in a webpage
so, just to give you some context even though my problem is not related to just this scenario. it depends on a much bigger spectrum.
Anyway, im developing on sugarCRM and im trying to edit the default onclick behavior of a slot in calendar module (you dont need to understand this to help me, so please keep reading). when i click on a slot, a modal dialog window opens that lets me log a meeting or a call.
So i tracked down the javascript behind this. ive used firebug and chrome, and they both give a list of all the JS files that are being used on a given webpage
for example i search for "SUGAR.collection" and firebug tells me its located in a file named "sugar_field_grp.js?v=FVh1Z-v5nA6bYov7-aFFqQ" i can see this piece of code resides in sugar_field_grp.js,
but the code im trying to change resides in "index.php?module=Calendar&action=index&parentTab=Activities", firebug actually tells me this is the file that has the javascript i want to change.
I can also right click view page source and i can see that piece of code inside the script tag. so considering this piece of code doesnt reside in a JS file, i cannot change it, its generated at runtime (i think) but there must be some source, there must be a file thats telling sugarCRM to generate this code
tl;dr how to track down a piece of javascript code that resides on pagesource and theres no JS file specified by firebug or chrome save for index.php (this file doesnt have that javascript either)
i know its been a long post
thanks for reading
Learn how to search for strings in files on disk on your machine.
On Linux, MacOS and most unixen the go-to tool for this is grep. This applies to any programming language you work with. For your case simply cd into the directory of your source code and do:
grep -r SUGAR.collection .
If you're using git as your source control tool then git grep is much faster.
On Windows there are various GUI tools you can use to search for text in files. Just google: grep for windows.
If you're using an IDE then just your IDE's find-in-files functionality.
To track down specific code using Chrome / Webkit go through the following two steps:
Client:
1. Search all static text sources
Open the Dev Panel using CTRL + SHIFT + I
Hit CTRL + SHIFT + F for a global search dialog to pop up
Right next to it you can set pretty printing of the JS code to on: button { }
Enter your search term or terms using regular expressions
Optional: Decide if you need a case insensitive search which has a greater searchspace and takes longer
Example:
2. Search the dynamic user-DOM contents
Go to the Tab 'Elements' hit CTRL + F.
Enter your search term (This will also search iframes, svg's etc... within the parent DOM)
3. Recommended:
Cross-reference the results of step 1. and step 2.
If a given string is present in both the DOM and the static sources, then you can assume that the content is not programmatically created on the client-side.
Server:
Many projects perform a media bundling step prior to content-delivery. They pack web-resources into the main file (e.g. index.php) to save HTTP roundtrips.
Use sourcemaps / and or search the entire codebase for a salient static string or a salient keyword near the static string to locate the original source files.
Searching files:
Locally, I generally use the rapid index, and heuristic search of JetBrain's IDE's (IDEA, PHPStorm,...) and Sublime. The grep-command tool can definitely not compete here in terms of performance. On Windows I additionally use Totalcommander and its archive/regex finding abilities.
When quickly looking up code on the server you may use something like:
grep -r -C10 --color=always 'keyword1|keyword2' htdocs/ | less -R
which will also provide you with line-context. two caveats: you may want to filter out binaries first and symlinks outside the scope will be ignored.

How to disable the JavaScript Minifier in CodeKit?

What's the best way to disable JavaScript minification in CodeKit? All those *-ck.js files it creates are making a mess of our repository's submodules.
Note that adding a rule to .gitignore doesn't work because its rules aren't inherited by submodules.
In CodeKit Preferences select Languages / JavaScript to edit the default settings for JavaScript handling. (These can be overridden for each file in a project.)
Change the setting for the second processing step (labelled "Then:") from "Concatenate + minifiy" to "Concatenate imported files". For any script file already in the project check whether it already has individual settings which still differ from this new default.
In this case, "*-ck.js"-files should only be created in case a source file imports another for concatenation but not for ordinary script files.
Alternatively you might specify a different output path for the generated ck-Files in CodeKit Preferences / JavaScript / Output Paths in order not to let the generated files clutter the source directory.
I believe the menu has been updated, but the answer from immo still stands. Under Javascript Language settings you can click a dropdown for output style and change it from minified to non-minified.
One workaround is to set the output path to something like codekit-ignore in Preferences > JavaScript > Output Paths, relative to the project's root folder.
Then add /codekit-ignore to .gitignore.
Easy to cleanup and feels better than find . -iregex '.*-ck\.js' -delete.
In the preferences see 'Skipped Items' under 'General' and add *.js to the list.
There are several ways to stop javascript minification in Code Kit but the easiest and simplest way to do so is simple to navigate to the javascript file you wish not to minify in the file view, and configure your Javascript Options to the right hand side.
This method provides benefits such as JSHint & JSLint without the minification and can be configured on a site by site, file by file basis giving you greater control.
Let me know if you have any further issues, i'd be happy to help.

Categories

Resources