JS Change hrefs to onclicks in HTML encoded entities - javascript

I'm looping through a database that have strings that contain HTML entities:
"<!-- SC_OFF --><div class=\"md\"><p>Here is an example link</p>\n\n<p>Here is some body text for you with <sup>superscript</sup> and a bit of <strong>boldness</strong> and some <em>italics</em>. I forgot to mention this regular link here http://example.com</a> so don't forget that one. sometimes there can be more than one <a href=\"http://example.com\">formatted link and http://example.com</p>\n\n<ul>\n<li>so there you go</li>\n<li>some sample text to work with</li>\n</ul>\n\n<p><del>strikethrough</del></p>\n\n<pre><code>if(canCode){\n //lol dont kid yourself\n}\n</code></pre>\n</div><!-- SC_ON -->"
that would be dynamically inserted into the DOM. I need to alter what the links do so basically all of these:
example
becomes:
<a onClick="myFunc('http://example.com')">example</a>
You can find the decoded string here:
http://codepen.io/YikesItsMikes/pen/NxaJXg
but I figure editing the original text might be easier? I have no idea honestly :s

After adding the html elements to DOM. Following code work (untested),
var $aTags = $('div.md').find('a');
$aTags.each(function() {
var $aTag = $(this),
href = $aTag.attr('href');
$aTag.on('click',function(e) {
myfunc(href);
e.preventDefault();
});
});
Updated code in your example (Tested)
var test = decodeHtml("<!-- SC_OFF --><div class=\"md\"><p>Here is an <a href=\"http://example.com\">example link</a></p>\n\n<p>Here is some body text for you with <sup>superscript</sup> and a bit of <strong>boldness</strong> and some <em>italics</em>. I forgot to mention this regular link here <a href=\"http://example.com\">http://example.com</a> so don&#39;t forget that one. sometimes there can be more than one <a href=\"http://example.com\">formatted link</a> and <a href=\"http://example.com\">http://example.com</a></p>\n\n<ul>\n<li>so there you go</li>\n<li>some sample text to work with</li>\n</ul>\n\n<p><del>strikethrough</del></p>\n\n<pre><code>if(canCode){\n //lol dont kid yourself\n}\n</code></pre>\n</div><!-- SC_ON -->")
$(document.body).append(test);
var $aTags = $('div.md').find('a');
$aTags.each(function() {
var $aTag = $(this),
href = $aTag.attr('href');
$aTag.on('click',function(e) {
myfunc(href);
e.preventDefault();
});
});
function myfunc(href) {
alert(href);
}
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}

Before inserting, you could run this replace:-
html = html.replace(/href=\"([^\"]+)\"/gi, 'onClick="myFunc(\'$1\')"')
using a group capture and $1
The group ( ... ) in the regex captures the value as 1 as 0 is always the full capture, in your case href="http://example.com"
In the second param then, you can use $0 for the full, or $1 for your capture group.

$('a').each(function () {
var href = $(this).prop('href');
$(this).click(function (e) {
e.preventDefault();
myFunc(href);
});
$(this).removeProp('href');
});

function myFunction(link) {
console.log(link)
}
var html = "<!-- SC_OFF --><div class=\"md\"><p>Here is an example link</p>\n\n<p>Here is some body text for you with <sup>superscript</sup> and a bit of <strong>boldness</strong> and some <em>italics</em>. I forgot to mention this regular link here http://example.com</a> so don't forget that one. sometimes there can be more than one <a href=\"http://example.com\">formatted link and http://example.com</p>\n\n<ul>\n<li>so there you go</li>\n<li>some sample text to work with</li>\n</ul>\n\n<p><del>strikethrough</del></p>\n\n<pre><code>if(canCode){\n //lol dont kid yourself\n}\n</code></pre>\n</div><!-- SC_ON -->";
$(html).filter(":not(comment)")
.find("a").each(function() {
var link = this.href;
$(this)
.attr({"href": "#", "onclick":"myFunction('"+link+"')"})
}).addBack().appendTo("body")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

$(document).ready(function () {
var szData="<div class=\"md\"><p>Here is an example</p>\n\n<p>Here is some body text for you with <sup>superscript</sup> and a bit of <strong>boldness</strong> and some <em>italics</em>. I forgot to mention this regular link here http://example.com</a> so don't forget that one. sometimes there can be more than one <a href=\"http://example.com\">formatted link and http://example.com</p>\n\n<ul>\n<li>so there you go</li>\n<li>some sample text to work with</li>\n</ul>\n\n<p><del>strikethrough</del></p>\n\n<pre><code>if(canCode){\n //lol dont kid yourself\n}\n</code></pre>\n</div>"
$('.content').html(szData);
$('.content').find('a').each(function () {
$(this).on('click', function (e) {
myfunc($(this).attr('href'));
e.preventDefault();
});
$(this).removeAttr('href');
});
function myfunc(szhref)
{
alert('myfunc')
}
});

Related

Im trying to use a click function which uses 'this' as to get the value after the last '/' in the URL by using split('/') or lastindexof('/')

I am triggering a click() function which will grab the users url link from an anchor tag and then I am trying to grab the end part of the URL which contains the username.
I can do this with out using $(this) but this has become a requirement and I need it done this way.
Please see the snippet to better understand.
$('a[href]').click(function(e) {
e.preventDefault();
var test = this;
// works fine
alert(test)
// doesn't work
alert(test.substring(test.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
Any ideas?
this will be a reference to the DOM element, the anchor, not to the anchor's href property.
Try var test = this.href;
$('a[href]').click(function(e) {
e.preventDefault();
var test = this.href;
// doesn't work
alert(test.substring(test.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
You can just do this:-
$('a[href]').click(function(e) {
e.preventDefault();
var test = this;
// works fine
alert(test.href) // use `test.href` instead of just `test`
// works fine now
alert(test.href.substring(test.href.lastIndexOf('/') + 1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>
I need to get the end part of the URL(john)
</p>
</div>
click here
The error is because test is the html 'a' element and not the url itself. Use test.href to access the url string.
Replace the javascript with:
$('a[href]').click(function(e) {
e.preventDefault();
var url = this.href;
alert(url.substring(url.lastIndexOf('/') + 1));
})
Refer the jsfiddle here for a working example.

How to get anchor text in a Session variable?

I am working on a project in which i have linked many pdf files in the master page.On clicking the anchor the page redirected to the specified page and displays pdf in iframe.Now i want the text in anchor tag to be displayed on the page where pdf is opened.
Consider I have an anchor which looks like this :
News Letter
Now i want the text " News letter" to be shown on the redirected page.
I think i could this by saving the text in session variable.But How can I save the anchor text in Session variable without specifying any id or class to the anchor tag? Can anyone help me please ?
You probably looking for QueryString instead of session, You are already passing path in QueryString, also pass the anchor text. You need to add this to url while you are creating the anchor tag.
News Letter
On server side
lblForAnchor.Text = Request.QueryString["aText"].ToString();
Edit you can not change the query string when it is created then you can change it when it is loaded in DOM in document.ready. Assign a class to your anchors to be specific.
$( 'a.someclass' ).attr( 'href', function(index, value) {
return value + '&aText=' + $(this).text();
});
Other way to do this on click of anchor.
$( 'a.someclass' ),click(function(event) {
window.location.href = this.href + '&aText=' + $(this).text();
});
You can try this
$("a").click(function (e) {
if($(this).attr("href").match(".pdf$"))
{
window.location.href = $(this).attr("href") + "&title=" + $(this).text();
e.preventDefault();
}
});
On server side in "Main_Content.aspx"
strTitle = Request.QueryString["title"];
You could Write the content dynamically with javascript:
News Letter
Javascript:
<script language="javascript">
function openWin(t,u) {
docstring='<iframe src='+u+'></iframe>';
win = window.open();
newdoc=win.document;
newdoc.writeln(t);
newdoc.write(docstring);
newdoc.close();
}
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
var theAnchor = elements[i].innerHTML;
var theHref = elements[i].href;
if(theHref.match(/\.pdf/)){
openWin(theAnchor,theHref);
}
}
</script>
Or call a different address with URL and test as parameters and generate the doc on the server side.
I'm not sure how this will behave with the link click but it might be worth a shot.
links should not have to be modified.

Add class only to numbers in HTML page except on links

I've tried this script inside Joomla to add a class to every number so that I can format them with CSS:
<script>
(function($) {
$(function() {
$('h1,h2,h3,h4,h5,h6,p,strong,i,em,b,span,sup,sub').each(function() {
var el = $(this),
html = el.html();
html = html.replace(/(\d)/gi, "<span class='number'>$1</span>");
el.html(html);
});
});
})(jQuery);
</script>
It work fine but I've got a problem with links where there are numbers such as:
www.miosito.it/index.php&articleid=2
In this case it make this:
www.miosito.it/index.php&articleid=<span class="number">2</span>
So the link is broken. How could I edit the script to fix it?

Inserting html content into another div using the href of a link to insert certain html of a div

Trying to insert the a certain div once a link is clicked. This link has the div id on its href. So I would like to fetch this data and use it to insert the html into a certain placement in my html DOM.
HTML:
<a class="hotspot article-1-slide-1" href="#product-1">
<span class="hotspot-label pp-icon icon-anime-left-arrow">article 1</span>
</a>
I would like to insert it into this space:
<article class="product-hotspot-display">
<a class="product-hotspot-close pp-icon icon-cross js-product-hotspot-close"></a>
// HERE
</article>
I think that .html() would be the answer. Using this code I get an error. What am I doing wrong?
//product link
$(document).on('click', '.hotspot', function (event) {
event.preventDefault();
var productId = $(this).attr('href');
var productHtml = $(productId).html();
productHtml.insertAfter('.js-product-hotspot-close');
panel.addClass('is-open');
//console.log(productHtml);
});
This should do the trick:
$(document).on('click','.hotspot' , function(event) {
event.preventDefault();
$(this).insertAfter('.js-product-hotspot-close');
});
This worked out for me:
var panel = $('.product-hotspot-display');
var slideWrapper = $('.slide-wrapper');
//product link
$(document).on('click','.hotspot' , function(event) {
event.preventDefault();
var productId = $(this).attr('href');
var productHtml = $(productId).html();
var contentHook = $('.js-product-hotspot-data');
contentHook.empty();
contentHook.html(productHtml);
panel.addClass('is-open');
});
I hope it helps anybody else!

Replace a URL if its found in the document Javascript

Hi i Usually use this code to replace a text in a page
$(window).load(function() {
var html = document.body.innerHTML;
html = html.replace( /Any Text/g, '???' );
document.body.innerHTML = html;
});
The problem i have is i cant isert a url instead of "Any Text"... my question is how do you do this:
$(window).load(function() {
var html = document.body.innerHTML;
html = html.replace( /http://subd.url.com/index.php?page=category/items/392/???/all/-1/-1/%20/%20/%20//g, 'http://www.newurl.com/foro/' );
document.body.innerHTML = html;
});
Thanks,
Also i know its better to use an Id like this..
$(window).load(function() {
$("#stID").attr("href", "http://www.newurl.com/foro/");
});
But this time i have to look in the entire body thanks.
jquery is running so if anyone know how to do it with jquery yes im open to jquery. thanks
Escape special chars with a \ like so..
html = html.replace( /http\:\/\/subd.url.com\/index.php?page=category\/items\/392\/???\/all\/-1\/-1\/%20\/%20\/%20\//g, 'http://www.newurl.com/foro/' );
This should replace all links on a page to the same destination link..
[].map.call(document.getElementsByTagName('a'), function(a){a.href = 'http://mysite.com'})
Well, I don't think you're being very clear about what you're trying to find and replace, but at face value, it looks like you are wanting to replace an exact url with another url, so you can do this (jQuery):
$(document).ready(function() {
$('a').each(function() {
var href = $(this).attr('href');
if (href=="http://subd.url.com/index.php?page=category/items/392/???/all/-1/-1/%20/%20/%20/")
$(this).attr("href","http://www.newurl.com/foro/");
});
});

Categories

Resources