Convert jquery to javascript, call a function on href click - javascript

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

Related

Change Click Function to hover (Vanilla Javascript)

I am using this code:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("div#logo1").onclick = function(){
hideAllImages();
document.getElementById("01").style.display="block";
removeNavHighlight();
document.getElementById("div#logo1").classList.add("my_active");
};
document.getElementById("div#logo2").onclick = function(){
hideAllImages();
document.getElementById("02").style.display="block";
removeNavHighlight();
document.getElementById("div#logo2").classList.add("my_active");
};
document.getElementById("div#logo3").onclick = function(){
hideAllImages();
document.getElementById("03").style.display="block";
removeNavHighlight();
document.getElementById("div#logo3").classList.add("my_active");
};
function hideAllImages() {
var items = document.getElementsByClassName('changing_text');
var itemsLen = items.length;
for(var i = 0; i < itemsLen; i++) {
items[i].style.display="none";
}
}});
Which working fine with click event but I want to convert it to be functional when I hover to the element.
What this function must to: for example, when I hover on an image other element must appear and previous element must become hidden.
This is Vanilla Javascript code.
Any suggestions? tried to change .onclick to .onmouseover but not working.
It's not .mouseover it's .onmouseover
Is it working for you to replace .onclick by .onmouseover?
These functions are always in format on<event>. It should be .onmouseover as the other answers have already said. Note that you'd be using mouseover if you were adding an event listener using the addEventListener function.

JS - if I first run search (highlight text) then .click on section doesn't wanna work

If I run search and highlight text:
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
highlightSearch();
}
});
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
then this part of code stop working:
$('.service-box').click(function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html());
});
It doesn't register .click() anymore. I can not find out what is wrong. Can You please help me resolve this?
Thanks!
You are using innerHTML and getting rid of all the event handlers. If you are going to use it, please delegate the events:
$(document).on("click", '.service-box', function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html());
});
Since I don't know what's the static parent, I have used document. Please replace it with a selector for a static parent instead.
The reason why it's not working is because you are using innerHTML for the highlighting, which destroys events of that element and also trigger generation of the DOM over and over again.
Because of this and more reasons I've developed mark.js, a keyword highlighter for search terms or custom regular expressions.

Catch click event on absolute position element

I have div and over it is link with absolute position div. I need to catch click event on link and get "href" attribute. I don't want to use any library only plain JavaScript. Is it possible?
I tried something like this but it catches only div outside of link.
window.addEventListener('load', function ()
{
document.addEventListener('click', $openExternalLink, false);
});
function $openExternalLink(e) {
alert(e.target.tagName);
}
HTML:
<div>Text</div>
<div style="position: absolute; left: ..., top: ..."></div>
Maybe this structure is terrible unfortunately I cannot influence it.
Thank you
document.onload = function() {
var myLink = document.querySelector("a");
myLink.addEventListener("click", function() {
var href = this.href;
})
}
Simply add an event listener to your anchor, then get its href attribute with this.href (or this.getAttribute("href"))
I'll assume you're fairly new to JavaScript? if so, definitely go check out http://CodeCademy.com/
Also, something I just though of, if you want to handle the link with a function (as it seems you do), do something like this instead:
document.onload = function() {
var myLink = document.querySelector("a");
myLink.addEventListener("click", function(e) {
e.preventDefault(); // Makes the event prevent the default link behaviour
var href = this.href;
externalLink(href);
})
}
externalLink(href) {
// Do something with your link.
// perhaps, window.location = href (or whatever)
}
To use for ALL links on a page (as per your comment), do the following:
document.onload = function() {
var links = document.querySelectorAll("a");
var i = 0, count = links.length;
for (i; i < count; i++) {
links[i].addEventListener("click", function(e) {
e.preventDefault();
externalLink(this.href);
})
}
}
externalLink(href) {
// Do something with your link.
// perhaps, window.location = href (or whatever)
}
Used querySelectorAll to target ALL anchor tags in the document, and then for-looped through them, adding an event listener to each. Keep in mind, this script needs some tweaking if you also want to support IE8. (using attachEvent("onclick"... instead of addEventListener, and replacing this with links[i] within the event)

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

How to get the action performed by an hyperlink in javascript

How can i get the action performed by an hyperlink inside an div using javascript
<div id="example">
<a href="#">a<a>
b
c
</div>
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
alert('a clicked');
}
links[1].onclick = function(){
alert('b clicked');
}
links[2].onclick = function(){
alert('c clicked');
}
Working Example
you can attach event handlers in the loop as well:
var links = document.getElementById('example').getElementsByTagName('a');
for(var i = 0;i < links.length; i++){
links[i].onclick = function(e){
var event = e || window.event;
alert(e.target.innerHTML + ' link was clicked!!!');
}
}
I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.
Goes to a mypage.html
Where As what you are asking by action performed is events. For that you should do something like this
Test Link
What this above link does is, executes a javascript function name test();
function test() {
alert('ok the action is performed');
return false; //so that the browser does not decides to navigate after the function is executed
}
Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery
$("#example a">.click(function() {
//now you have got the action performed work around.
// You can use this as you like
// $this represent the item that was clicked
});
For this functionality in core. #Headshota answers is good example.
#Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
// `this` inside this handler points to the <a> element that has been clicked
var href = this.href //where the link points
var target = this.target //if required
//do something with href and target
return false; //don't follow the link
}
etc...
$("#example a").click(function() {
alert("action");
});

Categories