Javascript: embedding a result of a function into a HREF - javascript

I have a javascript function that reformats a link. When a HREF link is clicked, I need to execute this method to finish creating the HREF.
Example JS method:
function fixURL (dest, val){
return dest + val;
}
I have an regular HREF and would like to combine the result of the above method to create:
<a href="http://www.site.com/" + fixURL('poo','no')>Click me!</a>
Is this possible and is it ideal to do so?

You can use an onclick handler. Note, you're generally better off not using inline event handlers like onclick="something...", so this is just for demonstration purposes.
Also, this will try to open a new window/tab with the search result.
<a target="_blank"
href="https://www.google.com/search?q=chris+rock"
rel="chris+rock|dave+chappelle"
onclick="fixURL(this)">Test</a>
function fixURL(el){
var vals = el.rel.split('|');
el.href = el.href.replace(vals[0],vals[1]);
}
http://jsfiddle.net/sxtuz/1/
The same effect, only using DOM event handlers. Note the id="fixme" attribute.
<a id="fixme"
target="_blank"
href="https://www.google.com/search?q=chris+rock"
rel="chris+rock|dave+chappelle">Test</a>
function fixURL(el){
var vals = el.rel.split('|');
el.href = el.href.replace(vals[0],vals[1]);
}
window.onload = function(){
document.getElementById('fixme').onclick = function(){
fixURL(this);
};
}
http://jsfiddle.net/sxtuz/

You can embed the result of a function into a href, yes, but the function call cannot be inlined within the HTML. Try this:
A link
<script type="text/javascript">
!function(links) {
links[links.length-1].href+=fixURL('arg1', 'arg2');
}(document.getElementsByTagName('a'));
</script>

If you keep it as:
Click Me!
You can then use jQuery to do:
$("a[href='http://www.site.com/']").attr("href", "http://www.site.com/" + fixURL('poo','no'))
Explanation:
The $("a[href='http://www.site.com/']") matches a element with an existing href equal to http://www.site.com/, then changes its href attribute to the second parameter that you pass in. In this case "http://www.site.com/" + fixURL('poo','no')

Related

Capturing the anchor tag

I've written a JavaScript code which over-ride the native alert() method.
I need to capture the HTML element which comprises the code of alert() execution.
First two cases are examples. I have printed the elements in console.log.
Case 1 - Capturing the <script> tag:
HTML: <script> alert(1); </script>
JS:
window.alert = function()
{
console.log(document.currentScript); // <script> is printed
}
Case 2 - Capturing the <img> tag:
HTML: <img src='1' onerror="alert(1)">
JS:
window.alert = function()
{
console.log(arguments.callee.caller.arguments[0].target);
// arguments.callee --> console.log()
// arguments.callee.caller --> onerror(event) {}
// arguments.callee.caller.arguments[0] --> event
// arguments.callee.caller.arguments[0].target --> <img>
}
Case issue - Capturing the <a> tag:
HTML: Click here for alert
JS:
window.alert = function()
{
console.log( // how to find <a> element)
}
Please don't suggest me to modify the HTML by including IDs for <a> or something similar. Consider that the HTML is purely static, and I can't modify anything. I can just add a JavaScript, and I just wan't to know how this can be done.
You might be able to find such alerts and convert them to click events. Something like this. Note the click event alert call could be made much more sophisticated and potentially use eval(), but i leave that for you to risk.
window.alert = (function(){
var selected = document.querySelectorAll("a[href^='javascript:alert('");
Array.from(selected).forEach(function(item){
var old = item.href
item.addEventListener("click", function(){ alert(old.substring(11)); });
item.href="javascript:void(0);";
});
var _alert = function(msg) {
console.log(msg);
console.log(arguments.callee.caller.arguments[0].target);
};
return _alert;
})();
test
You can use load event at window; click event at selector "a[href='javascript:alert(1);']" to get value of href attribute; call event.preventDefault() within click handler; String.prototype.match() to create array of values withing href attribute; define matches globally; new Function(); Function.prototype.call() to set this to <a> element; call .click() on selector : <a> element with matched parameters returned by .match()
window.alert = function() {
console.log(arguments, this)
}
window.addEventListener("load", function() {
a = document.querySelector("a[href='javascript:alert(1);']");
a.addEventListener("click", function(event) {
event.preventDefault();
var data = this.href.replace(/javascript/, "");
matches = data.match(/\w+(?=\()|(\(.*\))/g);
matches[1] = matches[1].replace(/\(|\)/g, "");
var fn = new Function(matches[0] + ".call(a, matches[1])");
fn();
});
a.click();
});
Don't use the href attribute to call JavaScript. It should be avoided. It is not recommended usage. Use the onclick event instead. See here: https://stackoverflow.com/a/10242595/5969411
<script>
window.alert = function(msg, element) {
console.log('Msg:', msg);
console.log('Element:', element);
};
</script>
Test 1
Test 2
Test 3
I've returned false from the onclick event above in order to repress the anchor from going to '#' URL directive, but you could easily return true instead here, if you wish.

Can't get the id name using onClick?

http://wthdesign.net/test/test.html
What I'm trying to do is append the id name into my url, but I'm getting "#undefined" instead?
The script I'm using:
function generateUrl()
{
var currentId = $(this).attr('id');
document.location.hash = currentId;
console.log($(this));
}
inside the html:
<a id="abc" onClick="generateUrl()" >this is an anchor btn</a>
<a id="abc" onClick="generateUrl(this)" >this is an anchor btn</a>
function generateUrl(elem)
{
var currentId = elem.id;
document.location.hash = currentId;
}
You pass the element to your function with "this"
If you debug, you'll find that this in this context is the window object. You can pass this into the function like so:
function generateUrl(el)
{
var currentId = $(el).attr('id');
document.location.hash = currentId;
}
<a id="abc" onClick="generateUrl(this)" >this is an anchor btn</a>
Alternatively, you can use jquery to replace your inline onClick like so:
$("#abc").click(function()
{
var currentId = $(this).attr('id');
document.location.hash = currentId;
}
That's because setting onclick HTML attribute is equivalent to set an anonymous function like this:
element.onclick = function(event) {
generateUrl();
}
As you can see, in your call you lost both event object and this contextual object, that becomes the global ones (window for the browsers).
Then you have several approach. First, don't use the HTML attribute, but set the click by JS instead, that is a better practice – avoid spaghetti code, when it's possible.
You're using jQuery, therefore:
$(function() {
$("#abc").click(generateUrl);
});
Plus, your function can be simplified:
function generateUrl() {
window.location.hash = this.id;
}
So your HTML will be just:
<a id="abc">this is an anchor btn</a>
If, for any reason, you can't / don't want remove the onclick from the HTML, you have to modify it a bit:
<a id="abc" onClick="generateUrl.call(this)" >this is an anchor btn</a>
In that way you're calling the function passing the right contextual object. Just as future reference, you could also pass the event as first argument:
<a id="abc" onClick="generateUrl.call(this, event)" >this is an anchor btn</a>
P.S.
Notice that without an href attribute in your a tag, the browser won't threat that tag as a "link".

Pass value to function from <a> tag, not from button

Consider the following link and associated Javascript function:
<a class="someClass" href="#" onClick="someFunc('someVal'); return false;">Run someFunc</a>
function someFunc(val) {
doSomething(val);
}
I would prefer to refactor the link and Javascript function to support some additional functionality (the link is actually in a div returned by AJAX):
<a class="someClass" href="#" someAttribute="someVal">Run someFunc</a>
$(".someClass").click(function(e) {
e.preventDefault();
// How to get value of someAttribute?
doSomething(val);
});
How can I get the value of someAttribute? Thanks.
Use attr() method
$(".someClass").click(function(e) {
e.preventDefault();
// How to get value of someAttribute?
alert( $(this).attr('someAttribute'));
});
DEMO: http://jsfiddle.net/buC8k/
API refrence: http://api.jquery.com/attr/
The clicked element is this. You may use the attr function :
var someValue = $(this).attr('someAttribute');

Jquery syntax and variables

I'm trying to make a FadeOut effect after clicking a link. But my syntax seems to be wrong. When i click, it fadeout, and go to a "~~nothing~~.html" page, it just dont get the value to compose the variable.
the id boo is attached to the tag (body id="boo") and in the css stylesheet the id #boo is set to display:none;
I'm using jquery-1.7.2.min
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').val() + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" value="374" href="#">Go to page 374</a>
the 374.html page is in the same folder. If possible, please explain what have i done wrong, and make it step by step. I'm new to jquery.
Thank you!
the .val() method only applies to fields, just putting a value attribute on any element will not be read with the val() method.
Instead use .attr('value').
Or, its better practice to use data-* attributes and use the data() method:
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').data('value') + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" data-value="374" href="#">Go to page 374</a>
The val() function won't give you that value from an anchor tag, use attr("value") to get the valuue of the a tag
$(document).ready(function(){
$('#go').click(function(e) {
e.preventDefault();
var url = $('#go').attr("value") + ".html";
alert(url)
$('#boo').fadeOut(600, function() {
window.location.href = url;
});
});
});​
Alternatively, you can use HTML 5 data attribute to store such kind of value
<a id="go" data-someValue="374" href="#">Go to page 374</a>
And you can access it in javascript like
var someVal=$("#go").data("someValue");
sample http://jsfiddle.net/LyPZB/1/
The a tag doesn't support the attribute value, you should do like this:
set the anchor like this
<a id="go" data-page="374" href="#">...
(data-xxx are custom attributes)
and get its value with
$('#go').data('page')
In this way it will work and you will respect the HTML standard (since the anchor shouldn't have the value attribute)
Try:
var url = $('#go').attr("value") + ".html";
instead of
var url = $('#go').val() + ".html";
From the jQuery docs -
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
There's an example here - http://jsfiddle.net/A8ArH/

capture link text and append to the URL as query string

I want to capture the text that is in between anchor link tag and pass it to the href value as query string so it looks like http://mysite.com/events/Pages/default.aspx?cat=cancer
The reason I can't add that manually is because the value in between and is dynamic. How do I capture that and append to the url using jquery or javascript??
or i can maybe, at the event of Cancer link being clicked, direct it to http://mysite.com/events/Pages/default.aspx?cat=cancer
 Cancer
$("a").on("click", function (e) {
e.preventDefault();
window.location = this.href + $.trim($(this).text());
});
Or you could replace the href attribute for each link:
$("a").prop("href", function () {
return this.href += $.trim($(this).text());
});
Then clicking each link will automatically direct the user correctly. Your selector ($("a") should be more specific, depending on your markup)
Example: http://jsfiddle.net/6U749/
Edit: If you have to do it inline, here's one way:
Cancer
You could do something like this:
$('.someClassImStickingOnLinksThatNeedThisBehavior').each(function()
{
this.href = $.trim(this.href) + $.trim(this.innerHTML);
});
Then, for any link, it would automatically update the HREF to the current HREF plus the value of the node.
You can do:
var yourlink = $("#youlink");
var href = yourlink.attr("href");
var text = yourlink.html();
yourlink.attr("href", href + "?cat=" + text);

Categories

Resources