Change the Image Link to "#" using jQuery - javascript

I validate image path whether it is image path or some other path. If it is the image then replace the particular href value to # But the # value is affected all links. How can i replace the image link to #
jQuery(document).ready(function($) {
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
jQuery('a').prop('href', '#');
}
});
});
Here is the
FIDDLE
Any Suggestion would be great.

use this
jQuery(this).prop('href', '#');
or
jQuery(el).prop('href', '#');

Try with this like this
jQuery(document).ready(function($) {
$("a").each(function() {
var href_value = $(this).attr('href');
if (/\.(jpg|png|gif)$/.test(href_value)) {
jQuery(this).prop('href', '#');
}
});
});

The reason all links get their href set to # is that you use jQuery('a').prop('href', '#'); when you find an image link.
jQuery('a') finds all a-tags in the entire page.
Try using your el variable instead. Something like:
if (/\.(jpg|png|gif)$/.test(href_value)) {
jQuery(el).prop('href', '#');
}

try the below code
el.href="#";
http://jsfiddle.net/Q3Zwh/3/

Related

Removing an href value, if it exists using jquery

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

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>

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

Javascript , jQuery - what have I done wrong?

$(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'));
});

Adding CSS Class using jQuery

Below I have included the jquery code I am using to add a css class to the link in the side column that equals the active url, but it's not working, and at some point it did.
Link: http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/
<script type="text/javascript">
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
if ($(this).attr("href") == location.href)
{
$(this).addClass("CurrentProject");
});
};
</script>
Well, besides that code missing braces and parens it can be done much simpler:
$(function(){
$("a[href^='" + location.href + "']").addClass("CurrentProject");
});
You have unclosed braces in your script:
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
var a = $(this);
if (a.attr('href') == location.href) {
a.addClass("CurrentProject");
}
});
});
and you could rewrite your script like this:
$('ul.right_submenu > li > a[href=' + location.href + ']')
.addClass('CurrentProject');
Following your link, my location.href goes to http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/ but your project link in the page points to http://www.liquidcomma.com/portfolio/project/trade_show_fabrications/1... that will make attr('href') != location.href.
In the other links, location.href will be ending with a slash whereas the link's href will not.
You should use something else to match your project other than the href attribute, if you expect it to change in the future (and it probably will).

Categories