html <a> link javascript function with parameter - javascript

I'm trying to pass one parameter (text variable) from a <a> tag. This is the code that I'm using:
<a onclick='javascript:Page_Change('Previous')' class='PageLink'>Previous</a>
Without the parameter 'Previous' is O.K and the function is working correctly. There is any possibility to pass the parameter value only using pure js?

If you want to do it inline you can do this:
<a onclick="javascript:Page_Change('Previous')" class='PageLink'>Previous</a>
But it's better to keep it seperate like this:
<a id="prev" class = "PageLink">Previous</a>
You may bind the event handler using the jQuery library
<script>
// jQuery
$('#prev').click(function() {
Page_Change('Previous')
});
</script>
or using standard JavaScript
<script>
// javascript
document.getElementById('prev').addEventListener('click', function() {
Page_Change('Previous')
}, false);
</script>

May I suggest this, where you can pass a number of links having different parameters.
<a data-param="Previous" class="PageLink">Previous</a>
<a data-param="Next" class="PageLink">Next</a>
var links = document.getElementsByClassName("PageLink");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function(e) {
Page_Change(e.target.getAttribute("data-param"))
}, false);
}

Related

changing class name and sending parameter in javascript

I would like to change the class of a tag and send a parameter i to the myFunction the tag is without id or name:
<a class="active" onclick="myFunction('i')"></a>
<script>
function myFunction(obj) {
}
</script>
using this in the function like myFunction(this,'i') doesn't work.
using this in the function like myFunction(this,'i') doesn't work.
That should work, you just need to amend the function to accept the element as an argument.
However you should note that on* event attributes are massively outdated and should be avoided where possible. Use unobtrusive event handlers instead:
Array.from(document.querySelectorAll('a.active')).forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
console.log(this.dataset.foo);
});
});
One
Two
Three
Update:
You mentioned in the comments that you're going to use jQuery AJAX, so you can simplify above with jQuery:
$('a.active').click(function(e) {
e.preventDefault();
console.log($(this).data('foo'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
One
Two
Three
You can do something like this:
function myFunction(obj) {
var data = obj.attr("data-param");
obj.removeClass("active");
alert(data);
}
$(document).ready(function(){
$(".test").on("click", function(){
myFunction($(this))
});
});
<a class="test active" href="javascript:void(0);" data-param="i">test</a>
Fiddle:
https://jsfiddle.net/u81g6qk4/10/
You can pass a reference to an HTML element by putting this is the function. Then you can use the element reference to do stuff to it without needing a id or name attribute.
someOtherClass is an assumed variable that contains the name of the class you want to add. Change it to whatever class or variable you want to use.
<a class="active" onclick="myFunction(this, 'i')"></a>
<script>
function myFunction(obj, param2) {
$(obj).removeClass("active");
$(obj).addClass(someOtherClass);
}
</script>
Use this if you do not want to use Jquery
<a class="active" onclick="myFunction(this, 'i')">Click Me</a>
<script>
function myFunction(element, str) {
console.log(str);
element.setAttribute('class', 'clicked');
}
</script>

How do I unobtrusivify this javascript?

I pulled this simple javascript function for showing or hiding a div from here. The function is:
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none"){
document.getElementById(d).style.display = "block";
}else{
document.getElementById(d).style.display = "none";
}
}
This requires making a link like this:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
It's my understanding that having the link call javascript like that is bad practice. I'd like to make the javascript unobtrusive following https://stackoverflow.com/a/688228/2063292. But, that template provides a way to make some javascript execute for any link with a specified ID (e.g. all links with id="test" will call some function). I need to have a way to allow any link to pass the name of a specific div to the function, as in the original example, but I don't know how to do it.
I would prefer the ID of the div to be in the hash of the link:
Live JavaScript Demo
<a class="reversible" href="#arbitrarydivId">
Click to show/hide.
</a>
using
function ReverseDisplay() {
var divId=this.hash.substring(1), div=document.getElementById(divId);
div.style.display = div.style.display=="none"?"block":"none";
return false;
}
or
Live jQuery Demo
$(function() {
$(".reversible").on("click",function(e) {
e.preventDefault();
$(this.hash).toggle();
});
});
Older suggestions
window.onload=function() {
var links = document.querySelectorAll(".reversible");
for (var i=0;i<links.length;i++) {
links[i].onclick=ReverseDisplay;
}
}
using
<a class="reversible" href="#">
Click to show/hide.
</a>
To hide something else, try
function ReverseDisplay() {
var divId=this.getAttribute("data-div"), div=document.getElementById(divId);
div.style.display = div.style.display=="none"?"block":"none";
return false;
}
using
<a class="reversible" data-div="arbitrarydivId" href="#">
Click to show/hide.
</a>
In jQuery the whole thing would be
$(function() {
$(".reversible").on("click",function(e) {
e.preventDefault();
$("#"+$(this.data("div")).toggle();
});
});
Depends on how unobtrusive you want to be. You could do this (using jquery for shorthand purposes):
<a href="#" id="someUniqueId1">
Click to show/hide.
</a>
<a href="#" id="someUniqueId2">
Click to show/hide.
</a>
<script>
$("#someUniqueId1").click(function(){ReverseDisplay("#DivICareAbout");});
$("#someUniqueId2").click(function(){ReverseDisplay("#AnotherDivICareAbout");});
</script>
But then you need to specify each and every link in your javascript. So I would recommend being a little more obtrusive, not with JS but with the href. Like this:
HTML:
<div id="foo">I am foo</div>
<div id="bar">I am bar</div>
<a class="reverselink" href="foo">Click to show/hide.</a>
<a class="reverselink" href="bar">Click to show/hide.</a>
JS:
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
$(function () {
$(".reverselink").click(function(e){
ReverseDisplay($(this).attr("href"));
return false;
});
});
See this fiddle: http://jsfiddle.net/V73uw/ (again, using jquery for shorthand. It's trivial to do with vanilla js too).
Use this javascript to do all that.
function processName(aName){
//do work like hiding.
console.log(aName);
}
var body = document.getElementsByTagName('body')[0];
body.addEventListener("click", function(event){
if(event.target.nodeName === "A"){
//do work with anchor element
processName(event.target.dataset.div);
}
event.preventDefault();
});
Then use this html as your links.
some link
You can define your javascript for this once then all the links only need data-div to send a name to processName.
Only bad thing is data attributes are really new for html so it might, or might not be what you want.
By the way. This is actually similar to how KnockoutJS works. You might want to try that out.

Javascript onclick for class and name

I'm new to JavaScript and am unsure how to do the following:
I've got two links with the same css "class" but different "name" attributes. I need to perform different functions to each one individually when clicked using unobtrusive Javascript. Is there anyway to do this?
Example code:
<a class="ClassName" name="link1">Link 1</a>
<a class="ClassName" name="link2">Link 2</a>
Lets say I need to output "This is link 1" to the console when I click link 1. And "this is link 2" when Link 2 is clicked.
Attach an event handler to the elements, and just check the name and do whatever you'd like
var elems = document.querySelectorAll('.ClassName');
for (var i=elems.length; i--;) {
elems[i].addEventListener('click', fn, false);
}
function fn() {
if ( this.name == 'link1' ) {
console.log('This is link1');
} else if ( this.name == 'link2' ) {
console.log('This is link2');
}
}
FIDDLE
You can do like in this JS Fiddle Demo , its pretty simple:
JS:
var anchorTags = document.querySelectorAll('.ClassName');
for (var i = 0; i < anchorTags.length; i++) {
anchorTags[i].onclick = function() {
alert(this.innerHTML);
}
}
Hope this helps.
It's not very performant but you can use name selectors. .className[name=link1] however, if you have multiple links the best way to handle something like this is to use event delegation. It's really easy if you have access to jquery
I would do something like
parent.on('click', '.ClassName', function(event) {
var button = $(this),
name = button.attr(name);
switch(name):
case link1
case link2
...
});
this way you don't have to assign individual events to the different links. You could also do something like this without event delegation if you really wanted to it would just be changing it to
var links = $('.ClassName');
links.on('click', function() {
...
});
Keep in mind that the latter will attach an eventHandler to each link.
If you don't have jQuery you can still do this you just need to grab the elements differently and handle attachEvent vs addEventHandler. Also, applying the delegation will require delving into the event.currentTarget object.
something like:
var parent = document.getElementById('parentid');
parent.addEventListener('click', function(event) {
if (event.currentTarget.getAttribute('class')indexOf('ClassName') > -1) {
... do stuff w/ that link here
}
});

Convert jquery to javascript, call a function on href click

I am trying to write a pure JavaScript function (means no jquery).When a user clicks a link ( a tag) I wanted to run a javascript function. I Googled for a solution but did't find what I was looking for. Below is the jquery solution, I want a pure JavaScript event listener which listens to a href click. There is no id or class attached to tags. ex: <a href='xxxx'>xxxx</a>
This is what I have (using jquery)
$('a').click(function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = $(this).attr('href');
if (regExp.test(href)) { e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i); } });
I need to convert the above jquery to javascript, basically I need to convert " $('a').click(function(e) " this to a pure JavaScript event listener.
Thanks.
Short answer:
var myFunction = function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = this.href; // please notice this replacement here
if (regExp.test(href)) {
e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i);
}
}
var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', myFunction);
}
You can use "document.getElementsByTagName" to get a nodelist of all "a" elements in the DOM,
then loop through them and use "addEventListener".
This has the advantage of being supported in browsers without support for queryselector.
Add an onclick event on anchor tags like this.
click me

How do I disable a link with javascript and css?

Do you know how to disable link for user only? I have
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">Banana</div>
So idea is that link /search/Banana is a valid link and I want to keep it for search indexing engines. However, I want when user click on link, the function searchoffertext_selected was called and nothing more happened.
To stop the link from taking its default action add return false; to the onclick event:
<div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;">Banana</div>
It's probably a better idea to put the onclick directly on the <a>
But an even better approach would be to use unobtrusive JavaScript to attach an event to the link via a selector.
See also: Stackoverflow: When to use onclick in HTML?
Using jQuery:
$('#selector').click(function(e){
e.preventDefault();
});
VanilaJS:
<a onclick="return false;">
Try this?
js
document.querySelectorAll('.searchoffertext > a').onclick = function(e) {
e.preventDefault();
searchoffertext_selected(this.getAttribute("data-fruit"));
}
html
<div class="searchoffertext">
Banana
</div>
HTML
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">
Banana
</div>
CSS
Use pointer-events, but this is unsupported in versions of IE older than 11.
.searchoffertext > a {
pointer-events: none;
}
JavaScript
Prevent the default action from executing when the link is clicked:
var links = document.querySelectorAll('.searchoffertext > a'), i;
for(i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function(e) {
e.preventDefault();
}, false);
}

Categories