Basic question so I feel dumb but..., Whats the proper syntax below in the href?
The href:
<html>
</html>
The Function:
function navClickListener(appendE, target, gotoURL) {
//doing stuff
};
When you really have to use inline JavaScript, use different quotes, eg ' or ".
Currently, the HTML attributes are marked by double quotes, as well as the JavaScript code.
Is effectively truncated to:
^ Because of this.
In this case, since you're using a JavaScript-URI, you can also use %22 instead of double quotes.
Demo: http://jsfiddle.net/pu3CM/
You'd be better off avoiding JavaScript in your "href" attributes.
<a href='#' onclick='navClickListener("navContent", "bodyContent", "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content"); return false;'>Click Me</a>
Using javascript:void(0); as the HREF value will prevent jumping or other undesired behavior from happening when the user clicks on the anchor. Use single quotes since you have double quotes in your JavaScript.
<a href="javascript:void(0);" onclick='javascript:navClickListener("navContent", "bodyContent" "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content");'></a>
Alternatively, you can do the entire thing in your JavaScript by binding a click handler. This would allow you to set a normal HREF value, which would be better for screen readers, and still allow the same functionality.
$(document).ready( function() {
$('.someclass').click( function(event) {
event.preventDefault();//Does the same thing as javascript:void(0); in the HREF value
var pageURL = $(this).attr('href');
navClickListener("navContent", "bodyContent", pageURL );
} );
} );
Related
I am having troubles pulling the value from a link. It's a CSS formatted page and I would really prefer to use a <a> than a <button>.
<button value="1" onclick="showDetails(this.value)">This works</button>
<a value="2" onclick="showDetails(this.value)">This doesn't work</a>
};
xmlhttp.open("GET","getdetails.php?q="+str,true);
xmlhttp.send();
How can I get the value of <a> when it is clicked and not having it go somewhere?
Only a select few elements, like <input>s, <textarea>s, and <button>s can have value properties:
console.log(
document.querySelector('a').value
);
<a value="val">a</a>
If you have to use the value attribute, use the getAttribute method instead of dot notation:
console.log(
document.querySelector('a').getAttribute('value')
);
<a value="val">a</a>
Another option would be to use data attributes instead, which would be more appropriate than value="s when working with an <a>:
console.log(
document.querySelector('a').dataset.value
);
<a data-value="val">a</a>
(also make sure to attach your event handlers properly using Javascript if at all possible - inline handlers are generally considered to be pretty poor practice - try using addEventListener)
To use addEventListener, select your a, and call addEventListener on it. For example, if your <a> has an id of details:
const details = document.querySelector('#details');
details.addEventListener('click', () => {
showDetails(details.dataset.value);
});
function showDetails(str) {
console.log('showing details for ' + str);
}
<a id="details" data-value="thevalue">click for details</a>
You can write a Javascript function to get the value from the link as follows:
function showDetails(a){
let value = a.getAttribute("value");
// view value
console.log(value)
}
<!--<button value="1" onclick="showDetails(this)">Button link</button>-->
<a value="2" onclick="showDetails(this)">Anchor link</a>
Your issues has 2 parts:
#1: Use of correct attribute
You should not use the value attribute in <a> tag, as it's not a valid attribute for HTML standard; try to use data-val instead. Attributes starting with data- allow us to store extra information on standard, semantic HTML elements without other hacks.
Example:
<a data-val="2" onclick="showDetails(this)">Test</a>
For the JS function, it can be written as:
function showDetails(obj) {
console.log(obj.dataset.val); // 2
}
References: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
#2: Prevent the <a> gets redirected
The initial choice of using <a> is incorrect, as <a> is designed to: (1) redirect to other page via hyperlink specified; or (2) go to certain section in the page using anchor name.
However, you can still stop the redirection using JavaScript (though not suggested). Edit your onclick function as below:
<a data-val="2" onclick="showDetails(this); return false;">Test</a>
Note the return false is added.
p.s. for better coding standard, you should separate JS from HTML structure.
Anchor tag does not have a value attribute, you can read about it in mdn. If you need to assign a value to an anchor tag you can use custom data attribute data-*. In order to get values from data-* in your javascript function can try something like this
const anchor = document.querySelector('a');
const str = anchor.data.value;
And then use it in your ajax logic.
const url = 'getdetails.php';
const params = `q=${str}`;
const http = new XMLHttpRequest();
http.open('GET', `${url}?${params}`, true);
// ... other logic
I'm using a widget (Purechat) that allows customers and operators to communicate to each other. I've ran into an issue where anchors' href values inside this widget are being appended with "http://%20", thus making them unclickable to our users. We are investigating the code, however, I would like a quick fix for this by replacing all href contents that contain "http://%20" and replace that portion of the href with an empty string so my anchors work.
What would be the best way to go about this?
$('a').attr('href', function(index, value) {
return value.replace("//%20", "");
});
You can run a foreach jquery function which runs over every anchor whose href starts with that string, then cut it with substring method and set it's href value again.
This should work:
$("a[href^='http://%20']").each(function(){
var oldHref = $(this).attr('href');
var newHref = oldHref.substring(10, oldHref.length);
$(this).attr('href',newHref);
});
Basically, I'm trying to replace a part of url in the middle ('#') with another one, and remove first part of url. Script replaces '#' with no problem but rfuses to remove the first part of url. Am i doing something wrong, or is there another solution for that?
html of it
<a class="link_imagelibrary" href="#pink_yellow_flowers.pdf?5612">Download pdf set</a>
on condition changes to
<a class="imgdownload" href="http://www.picturewall.com/pages/Botanicalhttp://#.com/s/files/1/0183/2687/files/passpink_yellow_flowers.pdf?5612">Download pdf set</a>
jquery
$(".imgdownload").each(function(){
this.href = this.href.replace('#', 'http://#.com/s/files/1/0183/2687/files/pass');
this.href = this.href.replace('http://www.#.com/pages/botanical', '');
});
It's supposed to happen on condition. Judging that the rest of the script works fine on the condition- looks like the problem is somewhere here
This line is not being matched
this.href = this.href.replace('http://www.picturewall.com/pages/botanical', '');
because it doesn't exist in your href: (Note the capitalisation of 'Botanical')
"http://www.picturewall.com/pages/Botanicalhttp://cdn.shopify.com/s/files/1/0183/2687/files/passpink_yellow_flowers.pdf?5612"
The href is expanding with this.href, so while you have:
<a href="#" ...
The DOM element's href property gets this:
<a href="http://example.com/your/page/wherever.php#" ...
The easiest way to handle this is to do it differently:
$(".imgdownload").each(function(){
this.href = 'http://cdn.shopify.com/s/files/1/0183/2687/files/pass' +
this.href.split('#').pop();
});
Here is a demonstration of the "problem":
$('a').each(function ea(){
console.log(this.href, this.getAttribute('href'));
});
http://jsfiddle.net/Gtr8V/
You'll note that element.getAttribute('href') does return the raw href attribute value, not the property. You could use this with .replace() instead of the this.href.replace() you were trying.
I want to put a string into a href="javascript:" when i append a li but i doesn't work at all....
ajoutEnf("myString");
function ajoutEnf(enf){
$('#laliste').append('<li>Enfant</li>');
$('#enf').popup('close');
$('#laliste').listview('refresh');
}
That code will produce:
javascript:propEnfant(myString)
Thus clicking the link, the script will look for a variable named myString. You probably want to use '<li><a href="javascript:popEnfant(\''+enf+'\')" ...
Another thing to be aware of: if popEnfant is defined inside your DOMReady event listener (which I don't know if it is) it will not be globally accesible, which is a requirement for javascript:... to work.
Demo
You can bind the click event using jQuery.fn.on:
ajoutEnf("myString");
function ajoutEnf(enf){
$('<a herf="#" data-icon="edit" data-rel="popup">Enfant</a>').on('click', function(event) {
event.preventDefault(); // Stop the hash from changing to "" (page.html#)
popEnfant(enf);
}).wrap('<li/>').parent().appendTo('#laliste');
$('#enf').popup('close');
$('#laliste').listview('refresh');
}
This way you dont have to string whatever enf and make sure that objects/arrays are passed on correctly.
Do some little changes: add slashes with single quotes.
$('#laliste').append('<li>Enfant</li>');
What?! I know, what a bad idea.
Firstly I have no control over the html that was output, its from a vendor and it is produced via their crazy system that our company has an agreement with. (let's not talk about the situation, I know it's not optimal)
In the html I have:
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
In my JS If I do:
console.log($("#notify").attr("onclick"))
I recive:
onclick(event)
Which makes sense, but I need to change the onclick's attribute, so it reads to something like:
onclick="location.href='index.php?foo=bar&zoobazz=moo';return false;"
better yet, if I could remove the onclick and replace the href attributes value with location.href.
This will give you the function in a string
$("#notify").attr("onclick").toString()
Grep the URL after that
If I understand your question correctly, you want to actually see what the onclick event is doing and append to it, not just replace it. I tried this in chrome and it works, but it's pretty much a hack. Basically, when you get a reference to the "click" or "onclick" event function (using either jQuery or pure JS), then you can to a ".toString()" on it to convert the function into a string. Then you just strip off the "function" definition using some trickery and you're left with what you need - "location.href='.......".
Then just append your additional parameters. Hopefully this leads you in the right direction.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var $target = $("#notify");
var funcBody = $target.attr("onclick").toString().split("\n")[1].split(";")[0];
$target.attr("onclick","").attr("href", funcBody);
});
</script>
</head>
<body>
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
</body>
</html>
document.getElementById('notify').onclick = function() {location.href='index.php?foo=bar&zoobazz=moo';return false;};
Does
$("#notify").click(function() { $("#notify").attr("onclick", "location.href='index.php?foo=bar&zoobazz=moo';"); return false;})
not do what you need it to do?
You can set onclick by using $("#foo").click = '';
You can change href by changing the attribute, using .attr(key, value);
http://docs.jquery.com/Attributes, and http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax
so
$('#foo').click = '';
$('#foo').attr('href', 'whateveryousetitto');
I may be reading too much into the question, but I think OP is asking how to get the event code so that it can be manipulated, not just replaced. When specifying "index.php?foo=bar", I don't think the value of bar is known. If this was a known value, then why read the onclick value at all?
alert($('#notify').click);
?