Using jQuery to change href after .load() call - javascript

I'm pretty new to web design but since some months I'm trying to learn some basic knowledge to work with html, css, JavaScript an so on. I've followed and tried to understand all the basic tutorials found on w3cschool and other introducting sites, with no particular problem with structure in html nor styling with css, but now I'm facing JavaScript and here's the question, but let me explain first what I'm trying to achieve.
On the site I'm triyng to conceive I've created a side panel which must contain some titles and short descriptions of articles taken from another site, with another domain.
Due to my very poor experience and to the informations found on the web, I thought that jQuery could help me in this task, in particular with its load() method. So, after saving a copy in .txt format of the source page where the titles are, I wrote a very simple code in my document's head:
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)");
$("#myDiv2 p").load("copyOfSite.txt .list a:eq(1)");
$("#myDiv3 p").load("copyOfSite.txt .list a:eq(2)");
});
This was working fine, except for the fact that the titles I am calling are relative links to articles with another domain, so they don't work in my site.
I've tried to specify a function in the second part of the load method but I couldn't find a way to prepend the domain of the other site to the href attribute I've loaded. I've only achieved to specify an url or to remove the loaded url with something like
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").attr('href','http://www.articlesdomain.com')}
)};
or
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").removeAttr('href')}
)};
but in both cases I cannot manage to call the href attribute of my loaded title and append to the articles domain. So I'm wondering if there's a way to achieve it or if my approach to the task is completely wrong.
Thanks in advance

You need to prepend the protocol and hostname to the already existing relative href's, right now you're replacing the entire href with the new url.
Use a function to get each href, and just prepend the hostname to what's already there :
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").attr('href', function(_,href) {
return 'http://www.articlesdomain.com' + href;
});
)};
note that the relative hrefs should start with /, otherwise you'll have to add that to the end of the prepended url as well

$(function () {
$('a.something').click(function (e) {
e.preventDefault();
});

Related

Add a class attribute to certain links

I have pages on my site that go through a translation proxy. I need the displayed text in certain links to not be translated. I can add class="notranslate" to the link and the translator will skip over it no problem. However, I have hundreds of pages created before I implemented the translator and I'll have hundreds more as I keep going along—manually adding the class is not really an option.
The links I'm specifically concerned with are ones whose display text are literal URLs or email addresses. The translator doesn't touch the href attributes so the links still work as expected, but the displayed string gets mangled. For instance, in Vietnamese, "organization#domain.com" is displayed as "tổ chức#domain.com," and a link whose display text should be "domain.com/committees" is translated to "domain.com/commitaries."
So I'm looking for a solution that finds a elements whose display text contains "#" or "/" and adds class="notranslate". I don't think I need too robust a solution as I otherwise don't use the "#" or "/" in link display text often, if ever, except in these situations. I would guess this could be done with Javascript, but I'm a JS beginner at best. An option that filters content on the backend through Wordpress could also be a nice solution.
This is simple using jquery, ideally this will need to load before your translations plugin.
Note: If you have jquery already loaded as most wordpress themes already do, then you can remove the first line from this code, which includes the jquery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("a").each(function() {
let text = $(this).text();
if(text.includes("#")) {
$(this).addClass('notranslate');
}
if(text.includes("/")) {
$(this).addClass('notranslate');
}
})
});
</script>

How to recursively get all the links present in a website using Javascript?

I'm looking for the way to recursively find all the links present on any given website. I know how to do this in java but I don't know how it can be done using javascript.
Consider this image represents a website directory and if we provide 'www.abc.com' ,then it should return following output.
www.abc.com\images
www.abc.com\files
www.abc.com\images\a.jpg
www.abc.com\images\b.jpg
www.abc.com\files\aa.txt
www.abc.com\files\bb.txt
Since the question is tagged jQuery, I'll use that. Simply target the a tags.
var linksList = [];
function addLink(url){
if(url!= "" && linksList.indexOf(url) == -1){
links.list.push(url);
scrapePage(url);
}
}
function scrapePage(url){
$.get(url,function(html){
var $iframe = $('body').append('iframe');
$iframe.contents().find("body").html(html);
$iframe.contents().find("body a").each(function(index,link){
addLink(link.href);
});
$iframe.remove();
});
}
$("body a").each(function(index,link){
addLink(link.href);
});
Pretty simple, a function to add links in our list, another to follow the links we add. I decided to put the content of the scraped page inside an iframe to keep everything restrained...
You'll want to add your logic to make sure it takes only links that are from the domain. You might need to play with the URL as it will not be absolute (but considered it is in my code). And so on.
In js getElementsByTagName("a")
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
In jquery $("a")
I think you cannot get all the links of a particular website. But you can get all the link of particular page like below :-
var allLinks = document.getElementsByTagName("a");
Hope it helps. It would be great if you elaborate your issue more.

Change all external links using jQuery

I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that.
For example, my website is example.com.
I want to change all external links to
http://example.com/p/go.html?url=http://externallink.com
without need for any changes on my blog post. I don't have any idea to start with.
SOLVED: https://gist.github.com/2342509 Thanks everyone :D I just need to change it a bit.
In jQuery you can try:
// DOM ready
$(function(){
$('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});
Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. This idea derives from the fact you want to have external links open automatically in a different tab/window.
If this is not the required functionality, you can use a custom data- attribute in a similar way. Only difference is you will need to loop each link, and get the data from it.
// DOM ready
$(function(){
$('a[data-href]').each(function(){
var anc = $(this),
href = anc.prop('href'),
dataHref = anc.data('href');
anc.prop('href', href + '?url=' + dataHref);
});
});
HTML example:
external link
And now you will probably need to add more information if that is still not what you want.
Going off of #Tim Vermaelan's answer, you could try this, which will check for every link that doesn't start with your website's URL without relying on it being target="_blank":
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');

Change element on page according to element in iFrame on same domain

reading a lot of posts and answers about accessing content of an iFrame,
I try and combine these to my particulair case.
Unfortunately I can't get it to work, so maybe I'm missing some mental ability to add the dots ;)
What I try to do is as follows:
The page loaded in my IFrame (same domain) contains a menu, where my active items have class="menuactive" data-rel="SomeName". My parent page contains a div with links (#portfolioslider) that have id's corresponding to the data-rel attributes of the links in the iFrame.
So where in the iframe the links are for instance Fashion, on the parent page my elements are <span id="Fashion">Fashion</span>, on which I want to add a class class="active" at the same time as my iFrame reloads and adds the class="menuactive" to a menu item.
This seems the most logical approach:
Javascript in pages loaded in iFrame:
$(function() {
$('div.menu a.menuactive').ready(function() {
$(window.self.top).contents().find('#portfolioslider a').each(function() {
$(this).removeClass('active');
$('#$(this).attr('data-rel')).addClass("active");
});
});
});
Bit this doesn't work at all,
I wished I could make a jsFiddle but I can't seem to find out how to construct an iFrame there.
Any thought would be greatly appreciated!, thanks guys
kind regards,
Jeroen
Yeh!
I fixed it, using:
$('div.menu a').click(function() {
$('a.active', window.parent.document).removeClass("active");
$('#' + $(this).attr('data-rel'), window.parent.document).addClass("active");
});
Cheers,
Jeroen

ajax code to change image on webpage in template

i have one website which is working on templates.
in the template there is one main image & i want to replace that main image on some pages only not on full website. what i am looking for is to change the main image to new image on page where i need with ajax.
when i see the css of that template i found following code to show image
.top-bg{
background:url(../images/top-bg.jpg)
top center no-repeat;
position:relative;
}
and on php page i found following line which bring image.
<div class="top-bg">
i need ajax / jquery code to change image.
my basic logic is, i will get that image URL from MYSQL databse and assign to one variable and then i will change the image which come from database, actually its one page displaying products and i want to display main image of product with ref to loaded product, i hope you will understand what i need at the end...
Thanks
Thanks for every one how reply, i found the solution
$(document).ready(
function(){
$('#imageContainer').css("background-image", "url(images/cube.jpg)");
}
);
this did trick for me what i need, any way thanks and also for -ve voting thanks... :((
While I think Ajax is the wrong solution for your problem, I'll offer you the following (which, at least, meets your question):
$('#changeImage').click(
function(){
$('#imageContainer').load('http://path.to.php/file.php #imageID');
return false;
}
);
Clicking an element of id="changeImage" will load the contents of id="imageID" from the php file located at the url of http://path.to.php/file.php into an element (presumably div, but whatever) of id="imageContainer".
That said, I'd suggest following #Nick Craver and #Aaron Digulla's advice and use CSS.
If you view source there's a working demo of jQuery's load on my site (posted in response to a different SO question) at http://davidrhysthomas.co.uk/play/loadDemo.html.
Edited in response to comment from OP.
To do this automatically, on page-load:
$(document).ready(
function(){
$('#imageContainer').load('http://path.to.php/file.php #imageID');
}
);
You don't need any JavaScript at all for this, just include another stylesheet (or <style> block) on the webpages you want the imaged changed on. Just have this in there:
.top-bg { background:url(../images/other-image.jpg); }
Or the <style> version:
<style type="text/css">
.top-bg { background:url(../images/other-image.jpg); }
</style>
As long as this is declared after that template stylesheet, that background property will override the template one, and you'll have your custom image on just those pages.
I think AJAX is the wrong approach here. AJAX should be used to load new data when the user interacts with the web page.
Your problem can be solved much more simple: If you can add an AJAX call to the code of the page, why not simply add a new CSS style:
.tob-bg {
background:url(../images/other.jpg) top center no-repeat;
}
Or create a second template and use that for all but the main page.

Categories

Resources