$(document).ready(function () {
$("href").attr('href', 'title');
});
$('a[href$=.jpg]').each(function () {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc).css('max-width', '300px').css('max-height', '200px').css('marginBottom', '10px').css('marginTop', '10px').attr('rel', 'lightbox');
$(this).replaceWith(img);
});
});
This is the jQuery code I have at the moment, which I want to change all links' href to the same as their title, before then embedding them in the page. Yet with the changing href to title bit in the code, it stops working. I'm new to Javascript so am definitely doing something wrong, just not sure what yet! Any help much appreciated!
Thank you guys
EDIT
This is the html that I want to change:
<p class="entry-content">Some interesting contenthttp://example.com/index.php/attachment/11</p>
You are changing it wrong, you are trying to select href elements instead of a.
This fix should do it:
$("a[title]").each(function() {
$(this).attr('href',$(this).attr('title'));
});
It will select all a elements with title and set the href with this value.
Here's a much more efficient way.
Since you're just replacing the <a> elements, there's really no need to change its href. Just select the <a> elements that end with jpg/jpeg, and use that attribute directly.
Example: http://jsfiddle.net/5ZBVf/4/
$(document).ready(function() {
$("a[title$=.jpg],[title$=.jpeg]").replaceWith(function() {
return $('<img />', {src:this.title, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});
Your .each() is outside the .ready() function.
You can accomplish the href change easily like this:
$(document).ready(function () {
$("a").attr('href', function() { return this.title; });
});
The .attr() method will accept a function where the return value is the new value of (in this case) href.
So the whole thing could look like this:
Example: http://jsfiddle.net/5ZBVf/3/
$(document).ready(function() {
$("a[title]").attr('href', function() { return this.title; })
.filter('[href$=.jpg],[href$=.jpeg]')
.replaceWith(function() {
return $('<img />', {src:this.href, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});
This line:
$("href").attr('href','title');
Is finding all href elements and replacing their href attr with the string 'title'. Since there is no such thing as an href element, Try this instead:
// for every anchor element on the page, replace it's href attribute with it's title attribute
$('a').each(function() {
$(this).attr('href', $(this).attr('title');
});
Check this out: http://jsfiddle.net/TbMzD/ Seems to do what you want.
Note: $(document).ready() is commented because of jsfiddle, you actually need it in your code.
Try:
$("a").each(function () {
var $this = $(this);
$this.attr('href', $this.attr('title'));
});
Related
What would the best way to remove an href that has a specific value using jquery if it is found in the DOM.
$(document).ready(function () {
$('a').each(function () {
var hrefValue = $(this).attr("href")
if (hrefValue == '/remove/thehrefvalue?when=now') {
//remove only a href containing this specific value
}
});
});
Kind regards
Instead of iterating through every a, you can iterate through only as which have that particular href attribute by altering the selector string:
$('a[href="/remove/thehrefvalue?when=now"]').remove();
$('a[href="/remove/thehrefvalue?when=now"]').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
now
now
notnow
now
(Not entirely sure what you're looking for. If you wanted to remove the <a>s, use the code above - if you wanted to remove the attributes but leave the <a>s alone, use removeAttr('href') instead of .remove())
$(document).ready(function () {
$('a').each(function () {
if ($(this).attr("href") == '/remove/thehrefvalue?when=now') {
$(this).removeAttr("href");
}
});
});
I try not to ask questions, but I can't figure out what should be very easy. I'm building a site for practice briannabaldwinphotography.com. I'm just trying to condense this so that I could just click on an anchor and it smooth scrolls to a <section> with an id the same name as the anchor. Ex: the 'about' li anchor has an href of #section_three and will scroll to the <section> with an id of section_three. I tried like 10 different variations and it won't work for me. Sort of what I'm looking for would be $(this).attr("href").offest().top}....etc. Here is the code I want to condense. Thanks.
$(function() {
$("[href='#section_three']").on("click", function() {
$("html body").animate({"scrollTop":$("#section_three").offset().top}, 1000);
return false;
});
$("[href='#section_two']").on("click", function() {
$("html body").animate({"scrollTop":$("#section_two").offset().top}, 1000);
return false;
});
$("[href='#section_four']").on("click", function() {
$("html body").animate({"scrollTop":$("#section_four").offset().top}, 1000);
return false;
});
$("[href='#section_one']").on("click", function() {
$("html body").animate({"scrollTop":$("#section_one").offset().top}, 1000);
return false;
});
});
If you use the attribute starts with selector (^=) you can get all elements with an href beginning with "#section_", bind a handler to those, then within the handler use this.href to get the href of the particular element that was clicked:
$(function() {
$("[href^='#section_']").on("click", function() {
$("html body").animate({"scrollTop" : $(this.href).offset().top}, 1000);
return false;
});
});
Note that this.href does the same job as $(this).attr("href"), but more efficiently: no need to create a jQuery object to access a property of the element that you can get to directly.
Since the href in each case matches the target element it makes it fairly simple
$("[href^='#section']").on("click", function() {
var targetSelector = $(this).attr('href');
$("html body").animate({"scrollTop":$(targetSelector).offset().top}, 1000);
return false;
});
If those elements have a common class or better path through parent class and tags you could improve the initial selector performance
I'm trying to make a script that, when you click on an anchor, a $.get function will get the anchor's href and then the href will be removed, but I cannot edit anything about the anchor from inside de get element. Example:
// make anchor disappear for example (doesn't work)
$('.belovedanchor').click(function(e) {
$.get($(this).attr('href')).done(function() {
$(this).hide();
});
});
// make an anchor disappear using a function (doesn't work too)
$('.belovedanchor').click(function(e) {
function do() { $(this).hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
I don't understand why $(this) change to work with the $.get function istead of the .click event.
How would you guys do it?
You have a couple problems. Edit: Only one problem -- I now see from your comment below that belovedanchor is not the actual selector in your code.
First, your jQuery selector for the click event handler is most likely incorrect. Change $('belovedanchor') to $('.belovedanchor') or $('#belovedanchor') depending if the anchor is identifiable by either class or element ID respectively.
Second, this in the do callback function does not refer to the anchor. In JavaScript, scope is set at the function level, so anytime you declare a new function, this will refer to that new scope.
Do this instead:
$('belovedanchor').click(function(e) {
var anchor = $(this);
function do() { anchor.hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
Simplified:
$('belovedanchor').click(function(e) {
var anchor = $(this);
$.get(anchor.attr('href')).done(function() {
anchor.hide();
});
});
This may work properly
$('.belovedanchor').click(function() {
var selectedancor = $(this);
var myurl = $(this).attr('href');
$.get(myurl, function() {
selectedanchor.hide();
});
});
if I use:
jQuery(document).ready(function() {
console.log($(this));
});
then in console I have object:
[Document mypage.html#weather]
how can i get for this last ID? In this example this is #weather. I would like use alert #weather in selector, for example $(data_from_console + '.add').val();
Do you want to get the last element that has an ID attribute?
If so:
$(document).ready(function () {
console.log($('body *[id]').eq(-1));
});
EDIT
On a closer look, are you looking for the hash tag? ie. if your URL is mypage.html#weather you want the #weather ?
In that case try:
$(document).ready(function () {
console.log(document.location.hash);
});
You can use last() method. Try this:
$(document).ready(function() {
$('body *').each(function() { //selects all elements in body which got id
var lastEle = $(this).last(); //selects last one of them
console.log(lastEle.attr('id'));//returns it's id to console log
});
});
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