Here in this html i need to get the image name arrow_down using jquery and set it in a variable x.Here in my code after getting the image name i have to use that name in if else condition
<a style="color: #FFFFFF; text-decoration: none;" id="imageDivLink" href="#">
<img name="arrow" class="img-swap" src="Images/arrow_down.jpg" width="13" height="13" border="0" alt="" /></a>
and
$('#imageDivLink').click(function () {
var x = $("img[src$='arrow_down.jpg'][name='arrow']");
if (x == arrow_down) {
$('#MainContent_IFTrendAnalysis').animate({ height: '+=120' }, 500);
}
else {
$('#MainContent_IFTrendAnalysis').animate({ height: '-=120' }, 500);
}
});
Any suggestion?
bart s is mostly right - but to complete the jquery:
$('#imageDivLink').on('click',function () {
var imgName = $(this).find('img').attr('name');
if(imgName === 'arrow_down') {
//do something
}
else {
//do something else
}
}
use attr("src") to get the src attribute.
$('#imageDivLink').click(function () {
var x = $("img[src$='Images/arrow_down.jpg'][name='arrow']");
if (x.attr("SRC") == "Images/arrow_down.jpg") {
$('#MainContent_IFTrendAnalysis').animate({ height: '+=120' }, 500);
}
else {
$('#MainContent_IFTrendAnalysis').animate({ height: '-=120' }, 500);
}
});
I would give the image an ID like below
<img name="arrow" class="img-swap" id="myImage" src="Images/arrow_down.jpg" width="13" heigh="13" border="0" alt="" /></a>
Then using jquery you can grab the attribute name like this
var imageName = $('#myImage').attr('name');
Hope that helps
YOu can use the .attr() function provided by jQuery.
You can create custom attribute & the access it in jQuery.
Example
Then in jQuery
$().jQuery(function(){
var v=$('#id').attr('CustomName');
});
HTML:
<img class="zoom_img" src="images/8.jpg" id="my_img" name="my_img"/>
jQuery:
To get the name by using class name use the below example:
$('.zoom_img').click(function(e){
var fileName = $(this).attr('src');
var fieldName = $(this).attr('name');
alert('FileName : ' + fileName + '\nFieldName : ' + fieldName);
});
To get the name by using field id use the below example:
$('#my_img').click(function(e){
var fileName = $('#my_img').attr('src');
var fieldName = $(this).attr('name');
alert('FileName : ' + fileName + '\nFieldName : ' + fieldName);
});
Note: When using field id, we can get the value either by using field id or this keyword.
Related
The following JS gives me a list of all the img alt text used on a webpage, showing either a name "name" or empty quotes "".
const altAtt = document.querySelectorAll("*[alt]");
const altText = Array.from(altAtt, (al, i) => al.getAttribute('alt'));
console.log(altText);
Question:
How do I get all the images with alt="" or alt="some name" and add them to a unordered list injected into the DOM?
I can create the structure document.createElement('ul'); etc. But no idea where to start adding the information into the list.
Somehow using li.innerHTML = altText[i];
Thanks in advance for any help.
I do have this using jQuery but really wish to write this in vanilla JS. The jQuery adds a Div element after each image which is what I want to eventually achieve with vanilla JavaScript :-)
$.each($("img"), function() {
var altText = $(this).attr('alt');
if (altText === "") {
$(this).after("<div class=\"no-alt-text\">This image is decoration</div>");
} else {
$(this).after("<div class=\"show-alt-text\">This image ALT text is: " + altText + "</div>");
$(function () {
$("div.show-alt-text:contains(\"undefined\")").each(function () {
$(this).removeClass("show-alt-text").html("<div class=\"empty-alt\">This image is missing an ALT attribute</div>");
$('div:empty').remove();
});
});
}
});
I think this is close to what you are looking for.
const imgElements = document.querySelectorAll("img");
const showAltText = document.createElement("div");
showAltText.classList.add("show-alt-text");
const noAltText = document.createElement("div");
noAltText.classList.add("no-alt-text");
noAltText.innerHTML = "This image is decoration";
for(let i = 0; i < imgElements.length; i++){
var altText = imgElements[i].alt;
if(altText === ""){
imgElements[i].after(noAltText.cloneNode(true));
}
else{
const element = showAltText.cloneNode(true);
element.innerHTML = "This image ALT text is: " + altText;
imgElements[i].after(element);
}
}
<!-- Alt Text -->
<img height="100" alt="test1" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- Alt Text -->
<img height="100" alt="test2" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- Empty Alt Text -->
<img height="100" alt="" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
<!-- No Alt Text -->
<img height="100" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
I am using this code to show a preview of an image URL.
<input name="input_19" id="input_2_19" type="text" value="" class="medium" placeholder="http://" aria-invalid="false">
<script>
jQuery('#input_2_19').blur(function() {
var src = jQuery(this).val();
var previews = jQuery(".previewImage");
var drawPreview = true;
var PreviousSource = jQuery(this).data('previousSource');
if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$") && src != "")
{
jQuery("#warning").html("Must be an image");
return false;
} else {
jQuery("#warning").html("");
}
jQuery.each(previews , function(index, value) {
if (src == "" && PreviousSource == $(value).attr('src'))
{
jQuery(value).remove();
drawPreview = false;
return false;
}
if( jQuery(value).attr('src') == src)
{
drawPreview = false;
return false;
}
});
if(drawPreview) {
jQuery('#prev').append('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
}
var previousSource = jQuery(this).data('previousSource', src);
});
</script>
<div id="warning"></div>
<div id="prev"></div>
It works well, but if I change the image URL then the second image will show up too and the first will stay.
How do I make it so only one image preview is shown?
https://jsfiddle.net/LucyTech/qohxryL4/4/
Also why doesn't it work with some images eg
https://ae01.alicdn.com/kf/HTB1q0ucSYrpK1RjSZTEq6AWAVXap/Mifa-Portable-Bluetooth-speaker-Portable-Wireless-Loudspeaker-Sound-System-10W-stereo-Music-surround-Waterproof-Outdoor-Speaker.jpg
what is wrong with this url? In the browser it shows an image so why does the code give an error?
Please use this javascript. That will give you result as per your expectation.
$('#input_2_19').blur(function() {
console.log(jQuery(this).val());
var src = jQuery(this).val();
var previews = $(".previewImage");
var drawPreview = true;
var PreviousSource = $(this).data('previousSource');
if(src.match("/\.(jpeg|jpg|gif|png)$/") != null && src != "")
{
$("#warning").html("Must be an image");
return false;
} else {
$("#warning").html("");
$('#prev').html('<img class="previewImage" style="max-width:50px;" src="' + src + '">');
}
});
Using append() will always add a new element. Maybe you should include the img tag in the initial html with its own id property and change its src property with attr(). You can use show() and hide() on an image element or you can wrap it in a div/span and hide this one.
Before appending the
below code should work.
jQuery('#prev').html('');
After this add your img tag
jQuery('#prev').html('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
The problem of the image not previewing for some the links I think is related to the regular expression that you wrote in the str.math I am not very good in so I can not help you with it but I took a look at your post's first comment "Jinesh", his/her regular expression seems to work. For the other problem, I wrote some piece of code for with comments to fix the the multiple image
// When you release the keyboard key
$("#urlInput").keyup(function(){
$("#warning").text(""); // Clear message div
var url = $("#urlInput").val(); // get url in the input box
if(isValidImageUrl(url)) // Validate the url
$("#prevImg").attr("src", url).show(); // Change src of th eimg tag and Show it
else
$("#prevImg").attr("src", "").hide(); // If the url is not valid, hide the img tag in the html
});
// When you get out the side the input box such as clicking outside or pressing tab key
$("#urlInput").blur(function(){
var url = $("#urlInput").val(); // Get the url in the input box
if(!isValidImageUrl(url)) // Validate the url
$("#warning").text("Must be an image"); // if the url is invalid show warning
});
// Valdiate url fucntion
function isValidImageUrl(checkUrl){
return checkUrl.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,10000}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$");
}
img{
width: 100px;
height: 100px;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="warning"></div>
<input id="urlInput">
<div id="prev">
<img id="prevImg">
</div>
I write a function to append some HTML code to page like below:
function addGiftList(className, imgURL, Kind) {
var $li = $('<li class="' + className + '">');
var $img = $("<img>", { src: imgURL })
var $br = $("<br/>");
var $input = $('<input >', { type: 'radio', name: 'gift', kind: Kind });
var $label = $("<label>").text("Test");
$li.append($img);
$li.append($br);
$li.append($input);
$li.append($label);
return $li;
}
All this will append to a div with className cycle-slideshow then I call $('.cycle-slideshow').cycle();, but nothing happens. Does anyone know why?
Can I create HTML elements with javascript then call jQuery cycle plugin?
HTML
<button>append</button>
<div class="myslider composite-example" data-cycle-fx="scrollHorz" data-cycle-slides="> div" data-cycle-timeout="2000">
<div>
<img src="http://malsup.github.io/images/p1.jpg" width=100%>
<div class="cycle-overlay">first image</div>
</div>
<div>
<img src="http://malsup.github.io/images/p2.jpg" width=100%>
<div class="cycle-overlay">second image</div>
</div>
</div>
CSS
body {
width: 200px;
margin: auto;
}
img {
width: 200px;
}
JS
// first call cycle
$('.myslider').length > 0 && $('.myslider').cycle();
function addGiftList(className, imgURL, Kind) {
var $div = $('<div class="' + className + '">');
var $img = $("<img>", {
src: imgURL
})
var $input = $('<input >', {
type: 'radio',
name: 'gift',
kind: Kind
});
var $label = $("<label>").text("Test");
$div.append($img);
$div.append($input);
$div.append($label);
// dynamically adding slider: this is a plugin method see documentation
$('.myslider').cycle('add', $div);
return;
}
// dynamic add button for example
$('button').on('click', function() {
// add function for example
addGiftList('myclass cycle-slide', 'https://placeholdit.imgix.net/~text?txtsize=15&txt=image%20added&w=200&h=150&txttrack=0');
})
Please see this link of my codepen. I have solved your problem.
http://codepen.io/prashen/pen/PNPbRR
I have the following markup
<div class="col-md-4">
<div class="row">
<img name="previewImage" alt="" src="" style="max-height:300px;max-width :350px;">
</div>
<div class="row">
<button name="btnPushPhoto" type="button" class="btn btn-default" tabindex="-1">Push</button>
<button name="btnRemovePhoto" type="button" class="btn btn-default" tabindex="-1">Remove</button>
</div>
</div>
When I click on the remove photo button, I'm able to set my image to null (in the server side), however at the client side, I'm having some difficulties locating the image tag, and refresh it.
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
var img = $(this).parent().parent().find('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Nothing seems to happen here. No error in the browser's console.
This is the output of console.log(img);
[prevObject: x.fn.x.init[0], context: undefined, selector: "[name=previewImage]"]
You should store the $(this) in some variable before post request since inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to :
_this = $(this);
Then you could use parents() instead :
var img = _this.parents('.col-md-4').find('[name="previewImage"]');
Hope this helps.
Try this:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
var $this = $(this); //Insert this line
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = $this.closest("div.col-md-4").find("img"); //USE $this
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
You should move img definition before the $.post function:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var img = $(this).parent().parent().find('[name=previewImage]');
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
I think the way you are searching/looking at the relationship needs to be edited slightly. There are a few jquery methods that may help but I usually like to map out the relationships in my head like below:
<div name="PARENT_of_PARENT_of_X">
<div name="Sibling_of_PARENT_of_X OR child_of_PARENT_of_PARENT_of_X>
<img name="Child_of_SIBLING_of_PARENT_of_X OR CHILD_of_PARENT_of_PARENT_of_X" />
</div>
<div name="PARENT_of_X">
<button ></button>
<button name="SOURCE X" >Remove</button>
</div>
</div>
You could use jQuery selector "closest"
https://api.jquery.com/closest/
$(document).on("click", "[name=btnRemovePhoto]", function () {
var clickedButton = $(this);
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = clickedButton .closest("div.col-md-4").find("img");
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Im trying to toggle between two images but need the js to work with many different images. How do I make it with a parameter with the id? This is what I got so far:
JS
function changeIt(id)
{
var theImg = document.getElementsByTagName('img')[0].src;
var x = theImg.split("/");
var t = x.length-1;
var y = x[t];
if(y=='red.gif')
{
document.images.boxcolor1.src='./pics/green.gif'
}
if(y=='green.gif')
{
document.images.boxcolor1.src='./pics/red.gif'
}
}
HTML
<img src='./pics/green.gif' name='boxcolor1' id='boxcolor1' border='0' />
<img src='./pics/green.gif' name='boxcolor2' id='boxcolor2' border='0' />
<img src='./pics/green.gif' name='boxcolor3' id='boxcolor3' border='0' />
As you can see now it only works for the first image (boxcolor1).. I want it to work for all images by the name or id tag.
Thanks for all the help!
Try:
function changeIt(id)
{
var theImg = document.getElementById(id),
x = theImg.src.split("/"),
t = x.length-1,
y = x[t];
if(y == 'red.gif')
{
theImg.src='./pics/green.gif'
}
if(y == 'green.gif')
{
theImg.src='./pics/red.gif'
}
}
Working example:
http://jsbin.com/ugofiz/edit