How to update many links in a web page - javascript

I am using MVC webgrid and an artifact of navigating the page is I have lots of urls that look like like:
►
I need to change entrystate=Templates to entrystate=Paging.
Is there a jscript way to make this change for all the links in a simple script ?
The links are being generated by the webgrid component and I have no access to it. They seem to be formed because the grid takes the url that invokes the action and uses it as a base url (entrystate and modelIn are routevalues invoking the action). I have no control over this. My only option seems to be fixing the html after it is created. I am stuck with this lame grid.

Try this:
$('a[href~="/SyntheticData/MasterDetail?"]').each(function() {
$(this).attr('href', $(this).attr('href').replace('entrystate=Templates', 'entrystate=Paging'));
});
I used a wildcard selector to partially match the href so it doesn't loop through links that are unrelated. You may need to adjust it.
oops, you aint using jquery perhaps?

I was hoping for something simplter but this looks like it will work:
var links = $("a[href]");
for (var i = 0; i < links.length; i++) {
var link = links[i];
var urlin = link.attributes.getNamedItem("href");
var urlout = urlin.value.replace("entrystate=Templates", "entrystate=Paging");
var urlout2 = urlout.replace("entrystate=Designer", "entrystate=Paging");
link.setAttribute("href", urlout2);
}
I ended up using (thx suncat100):
$('a[href*="entrystate="]').each(function () {
var url = $(this)[0].attributes.getNamedItem("href").value;
url = url.replace("entrystate=Templates", "entrystate=Paging");
url = url.replace("entrystate=Designer", "entrystate=Paging");
$(this)[0].setAttribute("href", url);
});
});

Related

JavaScript how to include hash in variable that detects current domain?

My goal is to detect an href click and do something if the link is an external link. I have the following JavaScript in place to detect external links:
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
I then use the following to do something if an external link is detected:
else if (href != isThisDomain) {
// do something for external links
}
This works for external links but also fires for internal links with a #. For example, if my site is www.example.com I DO NOT want this to fire if href is www.example.com/#anchor or www.example.com/category/#anotheranchor.
How do I change isThisDomain to cater for this hash?
Have you tried using document.location.hostname (which only gets the host name part of the URL and excludes everything else) and comparing it to the URL you have?
If you're doing this to every link on the page, you'll need to set an EventListener on all links that check the host property on them. If it's external, do whatever you need to. It looks like this:
function checkHref(e) {
var url = e.target.href,
externalUrl = e.target.host !== document.location.hostname;
if (externalUrl) {
console.log(e); // Place your logic here.
}
e.preventDefault();
}
var links = document.getElementsByTagName('a'),
i;
// Loop through all anchor elements and add an EventListener
for (i = 0; i < links.length; i++) {
var el = links[i];
el.addEventListener('click', checkHref, false);
}

How to obtain all the URLs generated dynamically in javascript menu?

I need to download all the images from the gallery of this site but I don't know how to obtain the URL of them or where these URL are stored on.
I tried to download the entire site with some programs but none of them seems to download even the menu.
Hope someone have any idea how to achieve this without having to do it manually one by one.
Here I can saw the code that produce the URLs:
<script type="text/javascript">
$(function(){
$(".text-frame").not(".default-frame").hide();
$('#menubar .button').hover(function(){
$(this).toggleClass("button-hover");
});
$('#menubar .button').click(function(){
$(".text-frame").hide();
$("#image-viewer").hide();
$(".button").removeClass("button-active");
var showTextframe = $(this).attr("rel");
$("#" + showTextframe).show();
$(this).addClass("button-active");
});
function showImages (imgLinks){
for (var i = 0; i < imgLinks.length; i++){
//$("#image-box").append($('<img>').attr('src', imgLinks[i]));
var $imgSelector = $('<a>'+ (i + 1) +'</a>')
.data('imglink',imgLinks[i])
.click(function(){
$("#image-box").find("img").attr('src', $(this).data('imglink'));
$("#image-links").find('a').removeClass('active');
$(this).addClass('active');
//alert ("I open Image" + $(this).data('imglink'));
});
$("#image-links").append($imgSelector);
$("#image-links").find('a:first').trigger('click');
}
}
$.get("plants_w_links.md", function(semillaMenu){
var markdownConverter = new Showdown.converter();
$semillaMenu = $(markdownConverter.makeHtml(semillaMenu));
$semillaMenu.find("img").each(function(){
var $menuimage = $(this);
var $menulink = $(this).parent("li").find("a");
var menuimages = $menulink.data("menuimages") || [];
menuimages.push($menuimage.attr("src"));
$menulink.data("menuimages",menuimages);
$menuimage.remove();
});
$semillaMenu.find("a").click(function(){
var menuImages = $(this).data("menuimages");
//$("#image-box").empty();
$("#image-links").empty();
if (menuImages){
$("#image-viewer").show();
showImages(menuImages);
}
});
$semillaMenu.addClass("sf-menu sf-vertical");
$('#semilla-menu').html($semillaMenu);
jQuery('ul.sf-menu').superfish({delay:10});
});
});
</script>
The function showImages seems to generate the URL but I don't know what to do with that.
I found here many question asking something similar but all of them talking about donwloading images with progressive URL (like blabla.com/image1.jpg, blabla.com/image2.jpg, etc.) but it is not the case, the images are generated without a pattern (or not any that I can obtain or deduce).
EDIT: I need to know how those functions work in order to run something similar in the Chrome inspect console that gives me all the URL instead the URL of the clicked option of the menu.
EDIT2: Someone in a IRC channel told me that the script may be jQuery, so I'm adding the tag.
var urls = new Array();
Array.prototype.forEach.call( document.images, function( img ){ urls.push( img.src ) } );
console.log( urls );
After execution these lines of code urls will contain sources of all images on the page.
Finally someone on the jQuery chat tell me how to solve my problem. Accesing directly to this link was the answer. The link seems to contain the structure of the menues that semillaMenu function format (aparently) and process to show the images on the site.
This doesn't solve my question yet, because it's only working for this case. What I wanted was a way to obtain the URLs with a script but it's solve my problem.
So I let it be unaswered if someone know how to make a script that gives all the image links without having to process manually the plants_w_links.md file.

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

How can I prepend an onclick event with a string of text

I have <a>s with onclick events:
Track Your Package »
How can I prepend those onclick events with http://www.example.com so that the result will be:
Track Your Package »
It has to be compatible with jQuery 1.4.2
Somebody else, had mentioned something like this, but I can't get it to work in 1.4.2:
var link = $("a"); // I don't have enough info to tell you how to precisely get this instance
var originalOnClick = link.attr("onclick");
var part1 = "window.open('"; // this is always the same, right?
var part2 = originalOnClick.substr(part1.length); // the remainder, beginning with TrackPackage.asp
var newOnClick = part1 + "http://www.example.com/" + part2;
link.attr("onclick", newOnClick);
Thanks.
I don't think window.open() is a good idea here. It will get blocked by most popup blockers and if you're using jQuery you shouldn't be using the inline onclick event anyway.
What you're trying to do can probably be achieved with a simple anchor link:
And then you can do something like this:
var prependUrl = function($link, url) {
var oldUrl = $link.attr('href'),
newUrl = url + oldUrl;
$link.attr('href', newUrl);
}
prependUrl($('#yourLink'), 'http://www.example.com/');
EDIT:
If you don't have control over the html and you need to do it like that then use replace() on the onClick attribute like:
$('a').attr('onClick', $('a').attr('onClick').replace('window.open(\'', 'window.open(\'http://example.com/'));
example: http://jsfiddle.net/elclanrs/AH4As/

Fetch and Replace href attribute value of <a> tag using prototype

I have a simple link inside my tml (apache tapestry specific) :
www.google.com
Now on the browser if I am trying to click the link, actually it's redirecting to
http://localhost:8080/..../..../www.google.com
Instead of it should open a new tab for that link.
So the logic which I am thinking is :
1) Fire a javascript on page load
2) Get the href value of anchor tag
3) Append http:// at the start, if it doesn't contains it.
So to do this, actually I want to use prototype (javascript framework), and I am bit new to this...
How can I write the function using the Prototype.js library?
You don't say where the value for your href is coming from. As you say you need to prepend an "http". Assuming the link is dynamically rendered, why don't you just do this server-side, probably much easier. In tml:
... href="${url}" ....
and in .java:
public String getUrl() {
return "http://" + url;
}
This is a much better approach than doing it client-side as what happens if the user has javascript turned off?
On the other hand, if it's a static link in your .tml, just write "http://www.google.com"!
Edit: In light of your comment below:
public String getUrl() {
if (!url.startsWith("http://") {
url = "http://" + url;
}
return url;
}
The above is just an example of what do do. You can either add another method to activityDetails which does this (e.g getExternalLinkWithProtocol()), or provide a wrapper method similar to the one above.
No reason to do this on the client side. Simply change your template to:
www.google.com
and if it's based on a property:
${hostname}
... adjust to fit your properties, etc.
window.onload = function(){
var links = document.links;
for(var i=links.length-1; i>=0; i--){
var link = links[i];
var href = link.getAttribute("href");
if(href.indexOf("http://") < 0){
link.href = "http://" + href;
}
}
};

Categories

Resources