Get image alt, add as parent class - javascript

I'm doing some CSS and I'm not great with JavaScript. However I'm not allowed to edit any of the plugin files, so I thought I could use some JavaScript to solve my issue of missing unique classes.
I just want to take the alt="" HTML attribute from an image and apply it as class="" HTML attribute to its parent <a> element.
So instead of:
<div class="wrapper-class">
<a class="img-parent">
<img alt="image 1" src="">
</a>
<a class="img-parent">
<img alt="image 2" src="">
</a>
<a class="img-parent">
<img alt="image 3" src="">
</a>
</div>
I need:
<div class="wrapper-class">
<a class="img-parent image-1">
<img alt="image 1" src="">
</a>
<a class="img-parent image-2">
<img alt="image 2" src="">
</a>
<a class="img-parent image-3">
<img alt="image 3" src="">
</a>
</div>
Here's the pseudocode I would like to do:
(1) $ Function = ('**.wrapper-class**')
(2) IF (**this**) contains **img**
(3) GET image **alt value**
(4) if (this) contains ('**a**')
(6) Replace **alt** value empty space with - and apply **alt** value to **a** element as class
(7) else = do nothing
How can I do something like this?

Seems like a simple each would do it, assuming all .img-parents have the img in question as their only child:
$('.img-parent').each(function() {
this.classList.add(this.children[0].alt.replace(/ /g, '-'));
});
console.log(document.body.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-class">
<a class="img-parent">
<img alt="image 1" src="">
</a>
<a class="img-parent">
<img alt="image 2" src="">
</a>
<a class="img-parent">
<img alt="image 3" src="">
</a>
</div>
(Also, it's called "psuedocode")

First, let me say that it's not a very good idea to use alt attribute value and use it as class name. Assuming the alt attribute gets generated from filename, the filename permits characters which are illegal to use as CSS class names.
I.e.: picture+label.jpg and picture.with.label.jpg are perfectly valid filenames. Let's say the gallery strips the file extension at least, you get picture+label and picture.with.label as alt attributes both of which cannot be used as class names because dot and plus sign have special meanings in CSS selectors.
So to be safe, you might want to do some escaping of the value before using it as class name.
I suggest:
(function addClasses() {
$('.wrapper-class img').each(function (i, image) {
var imageElem = $(image);
var altValue = imageElem.attr("alt"); // Use .attr, not .prop as alt is always a string.
if (!altValue)
return; // either skip to next if image has no alt value or use some default value
// Replace invalid characters here, i.e. using Regular expression
altValue = altValue.replace(/[^a-z0-9\-_]/gi, "_");
// .closest() allows the image to be wrapped in another element/s beside the link
imageElem.closest("a.img-parent").addClass(altValue);
});
})();
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="wrapper-class">
<a class="img-parent"><img alt="image-1"></a>
<a class="img-parent"><img alt="image-2"></a>
<a class="img-parent"><img alt="image-3"></a>
</div>

This should find images and add alt attribute to <a> parent's class
$('.wrapper-class img').each(function(){
$(this).parent('a').addClass($(this).prop('alt').replace(/\s/g,'-'));
//$(this).parent('a').addClass($(this).prop('alt'));
});
console.log($('.wrapper-class').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-class">
<a class="img-parent">
<img alt="im a flower" src="">
</a>
<a class="img-parent">
<img alt="image-2" src="">
</a>
<a class="img-parent">
<img alt="image-3" src="">
</a>
</div>

Related

Change img src when clicked jquery [duplicate]

This question already has answers here:
change img src on click
(5 answers)
Closed 4 years ago.
I have some HTML code:
<div class="text-center img-big">
<!-- IMAGE BIG -->
<img class="img-fluid img-big" src="" alt="">
</div>
<!-- IMAGE SMALL -->
<a id="getImg" href="" ><img src="img/asus.jpg" alt="" class="img-thumbnail thumb-product img-fluid thumb-first" width="100"></a>
<a id="getImg" href="" ><img src="img/asus-thumb.jpg" alt="" class="img-thumbnail thumb-product img-fluid" width="100"></a>
<img src="img/asus.jpg" alt="" class="img-thumbnail thumb-product img-fluid" width="100">
and this is my some jquery code :
<script type="text/javascript">
var imgSrc = $(".thumb-first").attr("src");
$(".img-big").attr("src",imgSrc);
$("#getImg img").on("click",function(){
tes = $(this).attr("src");
$(".img-big").attr("src",imgSrc);
});
</script>
I want to change src image big when image small clicked, but my code doesn't work properly.
What I did is to change id="getImg" to class="getImg" because id attribute should always be unique.
Instead of getting the click event of the image, I used the click event of <a>, then located the <img> using find().
I also added an id to the big image, because there are two instance of .img-big, which is an <img> and <div>, and <div> does not have a src attribute.
Lastly, I used e.preventDefault() to prevent the redirection when clicking a <a> tag
$(".getImg").click(function(e) {
var imgSrc = $(this).find("img").attr("src");
$("#bigImage").attr("src", imgSrc);
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-center img-big">
<!-- IMAGE BIG -->
<img id="bigImage" class="img-fluid img-big" src="" alt="">
</div>
<!-- IMAGE SMALL -->
<a class="getImg" href=""><img src="http://via.placeholder.com/100x100" alt="" class="img-thumbnail thumb-product img-fluid thumb-first" width="100"></a>
<a class="getImg" href=""><img src="http://via.placeholder.com/200x200" alt="" class="img-thumbnail thumb-product img-fluid" width="100"></a>
First, you have multiple elements with the same id attribute.
Second, tes variable here is not defined.
tes = $(this).attr("src");
Third, try placing your javascript at the bottom of the html page or place your javascript code inside the ready function:
$(document).ready(function(){
});
You don't need to give getImg, it can be done through onclick function. Try my code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-center img-big">
<!-- IMAGE BIG -->
<img class="img-fluid img-big" src="" alt="">
</div>
<!-- IMAGE SMALL -->
<script>
function change_img(param){
var src = $(param).prop('src');
$('.img-big').prop('src',src);
}
</script>

How to get images alt using jquery?

I'm trying to add data-title and data-lightbox and get Images alt inside.
the problem is, i have a similar outputs, from first image alt only!
How can we fix it?
jQuery(document).ready(function($) {
var imagesalt = $('.box a img').attr('alt');
$(".box a").attr("data-title", imagesalt);
$(".box a").attr("data-lightbox", imagesalt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<a href="#">
<img src="img1.jpg" alt="Text 1">
</a>
<div class="img-block"></div>
</div>
<div class="box">
<a href="#">
<img src="img1.jpg" alt="Text 2">
</a>
<div class="img-block"></div>
</div>
<div class="box">
<a data-lightbox="text 1" data-title="text 1" href="#">
<img src="img1.jpg" alt="Text 1">
</a>
<div class="img-block"></div>
</div>
<div class="box">
<a data-lightbox="text 1" data-lightbox="text 1" href="#">
<img src="img1.jpg" alt="Text 2">
</a>
<div class="img-block"></div>
</div>
I tried writing the code more than one way, but not useful
Thanks
Your query is ambiguous, that's why!
When you request the "alt" attribute with $(".box a img").attr("alt"), you're taking in many objects, sure, but attr() is returning only the first result.
In pure jQuery, you'd do it with .each():
$(".box a img").each(function(){
var imageAlt = $(this).attr("alt");
var parent = $(this).parent();
parent.attr("data-lightbox", imageAlt);
parent.attr("data-title", imageAlt);
});
That should give you the behaviour you expect.
Iterate over each of the divs with the class of 'box' - then find the image within it, get the alt text of that and apply it as the data attribute of the div. Note I put in a console.log to demonstrate the alt text is being found correctly. Ypu can use the console inspector to see that the data attribute is being applied to the divs correctly.
$(document).ready(function(){
$(".box").each(function(){
var imageAlt = $(this).find('img').attr('alt');
$(this).attr("data-title", imageAlt);
console.log(imageAlt);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<a href="#">
<img src="img1.jpg" alt="Text 1">
</a>
<div class="img-block"></div>
</div>
<div class="box">
<a href="#">
<img src="img1.jpg" alt="Text 2">
</a>
<div class="img-block"></div>
</div>
Try this:
$('.box a img').each(function(){
$(this).parent().find("a").attr("data-title", $(this).attr("alt");
$(this).parent().find("a").attr("data-lightbox", $(this).attr("alt");
})
The .attr() method gets the attribute value for only the first element in the matched set.
But, the .attr() method sets the attribute value for every element in the matched set.
enter link description here

How to add text to anchor with image?

I have an image link that I want to turn into image and text link.
Having this:
<a href="http://example.com/" class="link">
<img src="http://i.imgur.com/s3zp1u2.jpg" /></a>
I want to get this (notice 'Cat' text):
<a href="http://example.com/" class="link">
<img src="http://i.imgur.com/s3zp1u2.jpg" />Cat</a>
My code adds the text but removes the image:
$(function(){
$('.link').text('Cat');
});
Simplest would be to add an extra span
<a href="http://example.com/" class="link">
<img src="http://i.imgur.com/s3zp1u2.jpg" />
<span></span>
</a>
js
$(function(){
$('.link span').text('Cat');
});
AN alternative is to use append()
Use append instead of text.
$(function(){
$('.link').append('Cat');
});
http://jsfiddle.net/0g8yuq0o/1/
One way:
$(function(){
$('.link').append('Cat');
});
To what have already been suggested, I can only add a pure Javascript solution:
<a href="http://example.com/" class="link">
<img src="http://i.imgur.com/s3zp1u2.jpg" />
<span id="cat-001-text">Cat</span>
</a>
<script type="text/javascript">
document.getElementById("cat-001-text").innerHTML = "dog";
</script>

Setting 'src' of img tag dynamically using backbone templating

I am trying to set the src of img tag dynamically with backbone templating, but / is appended automatically for which img not loaded.The part of template looks like -
<script type="text/template" id="home">
.......
<% var d=names[0].get("image_link")+".jpg"
//d=d.substring(0 , d.length-1); tried to cut down last char
%>
<a href="#" class="thumbnail"><img class="img-responsive ui-corner-all" width="100%" height="auto" src=<%=d%> />
.......
</script>
The output -
<a href="#" class="thumbnail"><img class="img-responsive ui-corner-all" width="100%" height="auto" src="image1.jpg/" />
I couldn't figure it out how to exclude that / in img src. Any suggestion please.
That slash is actually there in the code. As you don't have any quotation marks around the attribute value, the / in /> becomes part of the value.
Add quotation marks:
<a href="#" class="thumbnail"><img class="img-responsive ui-corner-all" width="100%" height="auto" src="<%=d%>" />

Showing and hiding image after clicking event

I'm trying to hide language_arrow_bottom after clicking and show language_arrow_up and afterwards the other way around.
I cannot find the error in my code below? I know toggle in jquery but I don't want to use it for now.
Thanks in advance
I'm loading http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
HTML
<a id="language_arrow_bottom" href="#nogo" title="Other languages‎"><img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt="" /></a>
<a id="language_arrow_up" href="#nogo" title="Close‎" style="display:none;"><img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt="" /></a>
JS
$(document).ready(function ()
{
$('#language_arrow_bottom').click(function(event)
{
$('#language_arrow_bottom').hide();
$('#language_arrow_up').show();
});
$('#language_arrow_up').click(function(event)
{
$('#language_arrow_up').hide();
$('#language_arrow_bottom').show();
});
});
You need to hide the language_arrow_up element by default, not the image inside it
<a id="language_arrow_up" href="#nogo" title="Close" style="display:none;"><img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt="" /></a>
Demo: Fiddle
I don't know but I think you probably need to add return false; calls at the end of your functions. Other code looks good
Check this Fiddle
Just make a with the id and do the same procedure you tried with the tag
<div id="language_arrow_bottom">
<img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt="" />
</div>
<div id="language_arrow_up" style="display:none;">
<img src="web/images/up_arrow.jpg" width="13px" height="13px" alt=""/>
</div>
Agree with Arun above.
Also, this code may be working, but you are using the same image, "web/images/bottom_arrow.jpg", so visually it may look like it's not working. Try using separate content within the tag (or view the web inspector) to validate whether the code is working or not.
Another fiddle:
http://jsfiddle.net/8A8LS/1/
<a id="language_arrow_bottom"><img src="http://www.iconshock.com/img_jpg/REALVISTA/3d_graphics/jpg/128/arrow_icon.jpg" width="13px" height="13px" alt="" /></a>
<a id="language_arrow_up"><img src="http://petacross.com/images/bwd_arrow.gif" width="13px" height="13px" alt="" style="display:none;" /></a>
$('a').click(function () {
$('a img').show();
$(this).find('img').hide();
});
Change the code to set display "None" for "a" instead of the img as the image is inside the a tag and you are showing and hiding based on the "a" id.
<a id="language_arrow_bottom" href="#nogo" title="Other languages">
<img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt=""/>
<a id="language_arrow_up" href="#nogo" title="Close" `style="display:none;"`>
<img src="web/images/bottom_arrow.jpg" width="13px" height="13px" alt="" />
The same js code will work here after the above changes.
$(document).ready(function ()
{
$('#language_arrow_bottom').click(function(event)
{
$('#language_arrow_bottom').hide();
$('#language_arrow_up').show();
});
$('#language_arrow_up').click(function(event)
{
$('#language_arrow_up').hide();
$('#language_arrow_bottom').show();
});
});
This is because you have hide the image on load...you should use display none in 'a' tag not in 'img'

Categories