Load dynamic data on <a href="url_of_data"> click - javascript

I'm currently loading my page data dynamically clicking on an element like this:
<a onclick="load('url_of_data')">Some Text</a>
But for a better UX I now want to have an element like this:
Some Text&
and then just use preventDefault like this;
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
});
I got this code from this question.
But it does not work, the site is still reloading and not running the function.
I now apply the click handler everytime the dynamic content was loaded and it works fine.

You need to add return false at the end of your function
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
return false;
});

You will need to specify the container div to which the content will be loaded into.
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
//Replace "self" with the container you want to load the content into, e.g. $("#myDiv").load(href);
self.load(href);
});

I Think this will make the work.
$('a').click((e) => {
e.preventDefault();
const href = $(e.currentTarget).attr('href');
window.location.href = href;
});

I just needed to reapply the click handler everytime the dynamic content was loaded.
Now it's working fine

$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
window.location.assign(href);
});
It helps you

Related

Monitoring page use with jQuery/javascript

I plan to add some basic user usage of multiple html pages. To achieve this I want to introduce as little code changes to existing pages as possible. Here is my approach :
Import .js file that contains operations to add listeners to the page and when an event is fired then invoke a function :
<title>myTitle</title>
<input id="click" type="submit" value="click"/>
<input id="test" type="textbox" value="test"/>
<a id="href">href</a>
$('a').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
$('input').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
function sendData(dataToSend) {
console.log('Sending data \n '+dataToSend)
}
for now sendData is just a dummy function, but I plan to modify this to send an ajax request to server endpoint with the dataToSend value.
Is there an alternative method of monitoring what the user clicks instead of coding a tags and input tags ? There may be other input types that I'm not aware of that may get clicked that will not be tracked ?
fiddle :
http://jsfiddle.net/g2Rxc/167/
Because click events may be added after you've imported your listener code, you'll want to use event delegation on the document element.
Since you're running jQuery v 1.6, you'll need to use the delegate method:
$(document).delegate('*', 'click', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 1
Later versions of jQuery handle event delegation using the on method:
$(document).on('click', '*', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 2
I see that your click functions do the same thing so you can nest all the elements in a single click event:
$('a,input,textare,..,..').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
Try:
$("body").find("*").on("click",function()...
You just need to plan what do you want to track, before write the code. By doing that you are going to find which elements and events you really want to track. With that in mind you will write something like:
$('everyElementSeparatedByComma').on('everyEventSeparatedByComma', function(){
...
});
A real example:
$('a, input, textarea, form').on('click, change, keypress, submit', function(){
...
});

Generate url only when anchor is clicked

Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

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

Making link to go somewhere else than its default href

I want to grab the link text and append it to the URL and open the new URL with querystring added Onclick of the Original Link..How do I get the link text using javascript or jquery?
<a href="www.mysite.com/search.aspx?kwd=" onClick="location.href='http://mysite.com/search.aspx?kwd='+ Grab text 'kangaroo' and append here as QueryString>Kangaroo</a>
You can access the current anchor through this. The text can be then had through this.innerHTML.
Something like this...
Kangaroo
$('.your-url').click(function(event) {
event.preventDefault();
window.location= $(this).attr('href') + encodeURIComponent($(this).text());
});
I noticed that none of the other answers were encoding the text in the link to be a query-string parameter.
Inline (like your example) would look like this:
Kangaroo
return false should be unnecessary because once you change the location object scripts stop running and the page changes.
UPDATE
You can use $.trim() to:
Remove the whitespace from the beginning and end of a string.
Source: http://api.jquery.com/jquery.trim/
$('a.your-url').click(function(e) {
e.preventDefault();
url = $(this).attr('href') + $(this).text();
location.href = url;
});
To send the page to the link's href + text when clicked, this should work:
$("a").click(function(){
location.href = $(this).attr("href") + $(this).text();
return false;
});
But why not just set the hrefs correctly when the page loads, and get rid of all these onclick handlers altogether?
$("a").each(function(i, el) {
var $el = $(el);
$el.attr("href", $el.attr("href") + encodeURI($el.text()));
});
jQuery example:
$('a.link').click(function () {
var $this = $(this),
href = $this.attr('href');
window.location = href + encodeURIComponent($this.text());
event.preventDefault();
return false;
});
Demo

Categories