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

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/

Related

Get current URL and add something in front with JavaScript

For a multi-language website, I want two buttons for the two languages that exist on the website.
The standard url would be: mydomain.com/something (this would be in german for example) The english url for this is: mydomain.com/en/something
How can I set up the buttons to get the current url/ page (in this case /something and add /en in front of it? Everything I found was to add stuff after the full domain.
Thank you very much.
check Location Obj MDM docs
console.log(document.location.origin + "/en" + document.location.pathname)
I'm not sure what your end goal is but if it involves reloading the same page with the localisation in the URL (i.e. on button click the page reloads and the page's URL is changed to mydomain.com/en/something meaning that on your next button click, the page would need to reload and its URL would need to be mydomain.com/something again) then you may need to look into RegEx and running it against the current URL to then swap out the URLs in the button so that on click you go to the correct version of the domain.
If the end goal is to only get the current URL and toggle whether the localisation appears in the URL or not then take a look at the snippet below which should hopefully help you out a bit.
For some further reading, I think these resources may be helpful for you:
RegEx: Regular expressions guide
RegEx: Regex101 - this is essentially a playground for practicing and testing your RegEx.
Location Object: MDN or W3Schools
jQuery(document).ready(function($) {
var $languageToggle = $('#language-toggle');
var origin = location.origin;
var pathname = location.pathname;
$languageToggle.on('click', function() {
var $this = $(this);
var toLanguage = $this.data('to-language');
var currentLanguage = $this.data('current-language');
var localisation = '';
/**
* This if statement will help prevent the constructedUrl variable
* from ever having a url such as https://website.com//page
* (notice the double forward slashes after .com).
*/
if (toLanguage) {
localisation = '/' + toLanguage;
}
var constructedUrl = origin + localisation + pathname;
$this.data('to-language', currentLanguage);
$this.data('current-language', toLanguage);
$('#output').text(constructedUrl);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Click on the toggle button</div>
<button id="language-toggle" data-to-language="en" data-current-language="">
Toggle language
</button>
var myFunc = () => {
window.location.href = window.location.href + "place you text here"
}
Click the button and the page will be edited
<button onclick="myFunc()">click me</button>

JQuery Using passed parameter value to initialize a page via $(document).ready

I am trying to access or make a parameter value which was passed via an <a> visible within another javascript file. I can't figure out how to go about it.
I have the ff. line of code which goes to a new page: student_learn_topiclink.php everytime the link is clicked
var topicLink = $('<a>' + topicTitle+ '</a>').addClass('topic_link').attr('href','view/student_learn_topiclink.php?topicId=' + topicId).attr('target','_blank');
This is what shows in the address bar after clicking the topicLink
http://localhost/cai/view/student_learn_topiclink.php?topicId=5
I want to use the value 5 in student_learn_topiclink page's JS file.
How can I expose or make the topicId = 5 visible in student_learn_topiclink JS file?
In student_learn_topiclink.js, I'd like to do something like this,
$(document).ready(function(){
alert(topicId);
});
See this thread about retrieving URL parameters with javascript. For your specific example, try the following:
var url_string = window.location.href;
var url = new URL(url_string);
var topicId = url.searchParams.get("topicId");
console.log(topicId);
Example fiddle: http://jsfiddle.net/craftman32/yxrvbcun/1/
You can use like this :
var topicId = window.location.search.split('topicId=')[1];
console.log(topicId);

Embed a javascript variable into my html anchor href

I have a piece of HTML which should look something like the following when rendered by the browser:
<b>This is a test</b>Test over!
The problem I have is that foo.php is defined in a javascript var in the document. For argument sake, the name of the var is myPath. I'm trying to figure out how to get rid of the hard coded foo.php from the HTML above and have it read it from myPath instead.
I've tried different variations of escaping quotes and document.write() but haven't had much luck.
Is there a way to do something similar to:
<a href=" + myPath + "?bar=yay">
and have it render foo.php from myPath?
If you give your link an ID, you can use that in your JavaScript to reference the element and modify its href.
<a href="#" id="js_link">
And then your JavaScript could look something like this:
window.onload = function() {
var myPath = 'foo.php',
link = document.getElementById('js_link');
link.href = myPath;
}
Just use getElementByID then set the href property.
Check out this working example.
(function () {
var a = document.getElementById('mylink');
var fooLink = 'foo.php';
var link = fooLink + '?bar=yay';
a.href = link;
})();
You should be able to use inline script to output your javascript variable.
This might help How to output JavaScript with PHP

How to update many links in a web page

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);
});
});

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