I've been looking for a question like this but none of them answer my question.
Please forgive me as I sometimes lack the ability to explain myself.
I have a page in sub1.domain.com where all links are formatted as
<a href="/link?param=whatever">
and I'm using jQuery to change the base domain to sub2.domain.com before the /link part that's different to the host to all hrefs on the page. I found this snippet while researching the issue. This is the code:
$('a').each(function() {
$(this).attr("href", function(index, old) {
return old.replace("/link", "https://sub2.domain1.com/link");
});
});
And it works like a charm for static links but the thing is that the page is a search results page that dynamically loads new results even after the page has loaded.
How do I make it dynamic so that all links that are loaded by the search, are modified by this script automatically? In other words, how do I apply this script to links that appear after the page has loaded and new results are cominig in?
base href will not work in this instance as it somehow breaks the whole page.
Thank you.
You could actually bind this event to a click. So when clickinng the link it will run this function and change the link. This would then change any new link also as long as this is bound to a parent or the document for example below
$(document).on('click', 'a', function(e){
e.preventDefault();
var link = $(this).attr( 'href' );
link = link.replace("/link", "https://sub2.domain1.com/link");
window.location.href = link;
});
Welcome to SO. I'd advise you to create a custom event and trigger it on any search or any other action you need. This approach is going to provide you a good flexibility and readability.
const table = $('#table');
let counter = 1;
$('#btn').on('click', function() {
const row = $('<tr>');
const cell = $('<td>');
const link = $('<a>', {
href: '/linktest',
text: 'Test link ' + counter++
});
cell.append(link);
row.append(cell);
table.append(row);
table.trigger('table.updated'); //triggering custom event
});
table.on('table.updated', function() { //custom event handler
$('#table a').each(function() {
$(this).attr('href', '/whatever_you_want');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='table'>
<tr>
<td><a href='/link'>Test link</a></td>
</tr>
</table>
<button type='button' id='btn'>
Add row
</button>
I wonder why no one of the other answers mentions that jQuery allows us to target all element with the same querySelector such for example if you want to target all aHref Elements you can just add a space after the letter a just like $("a ")!
const newLink="https://www.mynewLink.com";
$("a ").attr("href", newLink);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a target="_blank" href="https://www.google.com">Google</a>
<br><br>
<a target="_blank" href="https://www.facebook.com">Facebook</a>
Related
I am trying to forward to a link when the div is clicked using a data attribute and jQuery, but am stuck a bit. Here is the code I have:
html:
<div class="clickable-icon" data-link="www.google.com">click to be forwarded</div>
jquery:
$('.clickable-icon').attr('data-link');
used google as an example for the link to go to. But how would I use jquery to help with this?
you can do:
window.location.href = $('.clickable-icon').data('link');
and as you want on click, write click event and get clicked element data-link attribute value:
$('.clickable-icon').click(function () {
window.location.href = $(this).data('link');
})
WORKING FIDDLE
You could use window.location.href like
$('.clickable-icon').on('click', function() {
window.location.href = $(this).data('link');
});
$('.clickable-icon').click(function(){
window.location.href = 'http://'+$(this).data('link');
})
I have some hyperlinks which have a common class name. This hyperlinks are created dynamically on my web page with mvc asp.net helpers.
Right now I want to write a script that would determine the particular link that was clicked and execute a javascript function when this link is clicked.
My code is below.
My mvc code that generate the link, please take note of the function passed updateWaitingState(this)
td> #AntiXss.HtmlEncode(customerchatname) #Html.ActionLink("chat", "StartChat", new { threadid = avisitor.ThreadID, email = AntiXss.HtmlAttributeEncode(email) }, htmlAttributes: new { target = "_blank", #class = "chat", operatorid = avisitor.OperatorID, connectionid = AntiXss.HtmlAttributeEncode(connectionid), threadid = avisitor.ThreadID, onClick = "updateWaitingState(this);" })</td>
My javascript function for this link is below, JQuery has been called above the link.
<script type='text/javascript'>
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
alert(parentid);
}
</script>
The problem is that the browser generates an undefined for the sender object. I have tried for hours debugging, I cant seem to find the problem.
When I run my code in the browser. The html looks like this
<tr id="kayode#yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515" href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com" onclick="updateWaitingState(this);" operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Waiting</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>00:00:10</td>
<td>271.0.0.1</td>
</tr>
Is not sender that undefined, its the value of parentid because the html for your action link does not have a data-parentid attribute. Modify the html to
#Html.ActionLink(..., htmlAttributes: new { ... data-parentid="SomeValue", onClick = "updateWaitingState(this);" })
Give anchor tag a unique id say 'a1' and try this :
document.getElementById('a1').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
DEMO
EDIT :- if you want to add event listener on class then do as :
document.querySelector('[class=chat]').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
DEMO
OR Try Pure Jquery Approach :-
$("a[class='chat']").click(function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
and make sure that there is a attribute i.e data-parentid in your anchor tag.
I had to correct this html that I generated. The problem was not from the javascript rather the html.
chat
This solved the problem. Thanks alot for all your contributions. I really appreciate !!!!.
I have a page with many links that execute certain actions on click. Example:
<a class="x" onclick="somefunction(does_something)" href="javascript:void(0)">x</a>
I want to use a javascript injection to click all of them on the page. So far, I tried:
javascript:document.getElementsByClassName("x")[0].click();
But that doesn't seem to work. What am I doing wrong?
If your JS is inline, you can simply call what you need right in the href...
<a href="javascript:functionName('parameter1','parameter1','parameter1')">
Click to execute JS</a>
...but not wise if the parameters aren't predefined by you. Definitely don't do this if your parameters take user input and update/execute against your database, but it does work.
First of all, I'd suggest using jQuery, it's a lot easier to understand. Next, you can't really 'click' links dynamically and run it's function. You need to simply run a function on all the links and use it's address.
window.open( $('.x').attr( 'href' ), '_blank' );
Iterating through all links and opening them inside a container...
jQuery
$('#some_link_container').find('a').each(function() {
var link = $(this); // This is the current link in the iteration
window.open( link.attr( 'href' ), '_blank' ); // Prepare for mass computer lag
});
HTML
<div id="some_link_container">
A link
A link
A link
A link
</div>
If you are trying to run a function onclick, it's best to use a event listener rather then onclick. Something like the following
Event Listener Demo
Here we listen to a click on any link inside our container, then we run a function.
$('#some_link_container').find('a').each(function() { // Each link inside our div container
var link = $(this); // The current link
link.on('click', function(e) { // When the link is clicked
e.preventDefault(); // Stop the link from forwarding to that page
goodbye( link.attr('href') ); // Run our function onclick
});
});
var goodbye = function(link) {
alert( 'Goodbye guest! Forwarding you to: ' + link );
window.open( link, '_self' );
}
This seemed to be a simple javascript but I feel so dumb to ask this question.. but I don't know why this is not working. I have a method that dynamically creates some hyperlinks on the page. The hyperlinks are suppose to call an executable with a url as parameter. So, I use href with a call to this function that has the code to call the executable.
Non-dynamic anchor tag code works just fine to launch an exe.
But, I need this to work with dynamic hyperlinks. I have tried to simplify the problem and created the following jsFiddle to demonstrate the issue. The link doesn't call my method. Am I missing something stupid? I want this to work in IE.
I already tried some solutions posted by some people saying: I should try href="#" onclick="myfunc();". Somehow that didn't work either.
Here is my code:
function myfunc(url){
alert(url);
};
function dynfunc(){
var value = "This is a link";
var url="http://www.google.com";
var table = $("<table id='tab1'></table>");
var row = $("<tr></tr>");
var valueColumn = $("<td></td>");
$('').html(value).appendTo(valueColumn);
valueColumn.appendTo(row);
row.appendTo(table);
$("#div1").append(table);
};
dynfunc();
Assuming you have this html :
<table id="dyn">
<tbody>
</tbody>
</table>
You can just use this JavaScript for the Dynamicly added <a/>, this way you add one click handler instead of several.
<script>
$(function() {
var tbl = $('#dyn'), tbody = tbl.find('tbody');
var addLink = function(url, val) {
var tr = $('<tr/>'),
td = $('<td/>').appendTo(tr),
a = $('<a/>', {href: url}).html(val).appendTo(td);
}
tbl.on('click', 'a', function() {
alert($(this).attr('href'));
});
//some ajax that calls addLink
});
</script>
DEMO HERE
Change This line :
$('').html(value).appendTo(valueColumn);
To :
$('').html(value).appendTo(valueColumn).click(function(){myfunc(url) });
We associate a click event to your <a> after append and on every click , myfunc(url) will be called .
i have a div for which i set value dynamically during run time, if there is value than i have enable or create a link which will have onclick method where i will call a javascript method.
how to do this in jquery or javascript?
I set value to a div like the following,
document.getElementById('attachmentName').innerHTML=projectInforamtionMap.Cim_AttachmentNames;
this the div :
<tr>
<td align="left"><div id="attachmentName"> </div></td>
</tr>
Kindly help me to find and fix.
Best Regards
You can set a onclick function:
document.getElementById('attachmentName').onclick = function() {};
Assume that your function are previously define like this
function foo(){alert('function call');}
After adding innerHTML
In Javascript
document.getElementById('attachmentName').setAttribute('onclick','foo()');
In Jquery
$("#attachmentName").attr('onclick','foo()');
You have several alternatives
JavaScript:
// var elem = document.getElementById('attachmentName');
elem.onclick = function() {};
elem.setAttribute('onclick','foo()');
elem.addEventListener('onclick', foo, false); // The most appropiate way
jQuery:
// var elem = $('#attachmentName');
elem.click(foo);
elem.on('click', foo);
$('body').on('click', elem, foo);
Between the 3 jQuery alternatives, the last is the best one. The reason is due to the fact that you are attaching an event just the body element. In this case, it does not matter but in other cases, you are probably willing to attach the same event to a collection of elements, not just one.
Therefore, using this approach, the event is attached to the body but works for the elements clicked, instead of attaching the same event to every element, so it's more efficient :)
$('#attachmentName').click(function(){
//do your stuff
})
jquery way:
$("#attachmentName").click(function() {
some_js_method();
});
You can do this without inserting link in the div in following way
document.getElementById("attachmentName").onClick = function () {
alert(1); // To test the click
};
You can achieve it with the help of jQuery as well in the following way.
$("#attachmentName").click(function ()
{
alert(1);
});
for this you have to include jQuery liabray on the page. refer jQuery.com
Still if you forecefully want to include the link in Div then following is the code for it
var link = $("<a>"+ $("#attachmentName").text() +"</a>");
$("#attachmentName").html($(link);
link.click(function () {
alert(1);
});
Hope this would help.
as i was converting a classical asp details page to a one-page ajaxified page, i converted the existing links in the page to get the details loaded in the DIV in the same page. i renamed the href tag to dtlLink and got that data in the jquery load() function.
detail.asp (server.urlencode is added and required here )
<a href=""#"" onclick=""javascript:LoadDetails(this)"" dtllink="detail.asp?x=" & Server.URLEncode(Request("x"))&y=" & Server.URLEncode(Request("y")) > link text </a>
parent.asp (it has some extra code for holdon.js spinner image, button enable/disable, results div show/hide)
Jquery
function LoadDetails(href) {
//get the hyperlink element's attribute and load it to the results div.
var a_href = $(href).attr('dtllink');
console.log(a_href);
$('#divResults').html('');
DisplayHoldOn();
$('#divResults').load(a_href, function (response, status, xhr) {
$('#divCriteria').hide();
HoldOn.close();
if (status == "error") {
var msg = "There was an error: ";
$("#divResults").html(msg + xhr.status + " " + xhr.statusText);
$('#divCriteria').show();
$("#cmdSubmit").removeAttr('disabled');
}
});
}