I am trying to loop through an elements children to get there attr value. My HTML looks like this:
<div class="deal">
<img src="/images/deals/xbox-one500-gb-black.png" alt="Xbox One 500 GB Black box art/packaging" title="Xbox One 500 GB Black" height="60" width="40" class="console" />
<img src="/images/deals/xbox-one-additional-controller.png" alt="Additional Controller box art/packaging" title="Additional Controller" height="60" width="40" />
<img src="/images/deals/xbox-one-fifa-15.png" alt="FIFA 15 box art/packaging" title="FIFA 15" height="60" width="40" />
</div>
I would like to get the title attr off all items and combine into 1 title.
here is my script:
$(".deal").each(function() {
var test = $(this).attr('title');
}
console.log(test);
Am i approaching this in the right way?
jQuery.map allows you to enumerate a set of elements and perform an action on each one. In your case you want to pull out the title and join those items together.
In this example I've simply joined them with a comma.
var all = $('.deal img').map(function(){
return $(this).attr('title');
}).get().join(',');
alert(all);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="deal">
<img src="/images/deals/xbox-one500-gb-black.png" alt="Xbox One 500 GB Black box art/packaging" title="Xbox One 500 GB Black" height="60" width="40" class="console" />
<img src="/images/deals/xbox-one-additional-controller.png" alt="Additional Controller box art/packaging" title="Additional Controller" height="60" width="40" />
<img src="/images/deals/xbox-one-fifa-15.png" alt="FIFA 15 box art/packaging" title="FIFA 15" height="60" width="40" />
</div>
$.each loops over the result of the selector, which in your attempt was the container element, not its children. You want to adjust the selector to find the children img tags, build up an array of their titles and finally join the array together with commas or whatever separator you like:
var combined = [];
$(".deal img").each(function() {
combined.push($(this).attr('title'));
});
var combinedStr = combined.join(", ");
$("#title").text("Above: " + combinedStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="deal">
<img src="http://lorempixel.com/60/40" alt="Xbox One 500 GB Black box art/packaging" title="Xbox One 500 GB Black" height="60" width="40" class="console" />
<img src="http://lorempixel.com/60/40" alt="Additional Controller box art/packaging" title="Additional Controller" height="60" width="40" />
<img src="http://lorempixel.com/60/40" alt="FIFA 15 box art/packaging" title="FIFA 15" height="60" width="40" />
</div>
<div id="title"></div>
you are approaching the right way, but you are throwing your test var out with each pass. Also, you want to make sure your selector matches the img elements, and not the parent div.
// this is just debugging code specific to SO
var console = {
"log": function(i) {
var li = $('<li />');
li.html(JSON.stringify(i));
li.appendTo('#logger');
}
};
// this is the answer
var titles_as_array = [], titles_as_string='';
$('.deal img').each(function(el){
titles_as_array.push( this.title );
});
titles_as_string = titles_as_array.join(' ');
console.log( titles_as_array );
console.log( titles_as_string );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="deal">
<img src="/images/deals/xbox-one500-gb-black.png" alt="Xbox One 500 GB Black box art/packaging" title="Xbox One 500 GB Black" height="60" width="40" class="console" />
<img src="/images/deals/xbox-one-additional-controller.png" alt="Additional Controller box art/packaging" title="Additional Controller" height="60" width="40" />
<img src="/images/deals/xbox-one-fifa-15.png" alt="FIFA 15 box art/packaging" title="FIFA 15" height="60" width="40" />
</div>
<ul id="logger"></ul>
Related
I want to show div with an image, it's name, it's size and it's download link with jquery.
for that, I have made below code
var image = 'image/example.png'
$('#download').attr("href", result2);
$('.image').attr("src", result2);
var name = result2.replace('image/', '');
$('.name').text(name);
$('.filename').css('display','block');
<div class="filename" style="display: none;">
<img src="" class="image" width="100PX" height="100PX">
<b class="name">example.png</b>
<span class="size"></span>
DOWNLOAD
</div>
and my image is
everything is working fine except image size I don't know how can I get image size because when I was searching to get image size with it's MB, KB or in bytes with jquery it shows me a result in this formate $("#selector")[0].files[0].size but in my case, there is no files[0] is available so how can I find image size?
You can use fetch to get the reponse size. Since you make a request with an image path, the response size will points to the image size.
fetch($('img').prop('src')).then(function (response) {
console.log('size:', response.headers.get("content-length"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">
Another way to get the image width/height is: Using Image class:
var image = new Image();
image.onload = function () {
console.log('width:', this.width);
console.log('height:', this.height);
console.log('more information about this image:');
console.dir(this);
};
image.src = $('img').prop('src');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">
I have 10 images of an empty black square. Below them, I have 10 black boxes labeled 0-9. My goal is to allow the user to click on a numbered square, and select which blank square he wants to place it.
The user must be able to do this with every numbered square. (I have a math problem that I want the user to solve by clicking the images and put them where they need to go to solve the equation). My train of thought was to obtain the image clicked by using getElementId and storing it into a variable, and continue the process.
I'm not sure if this is possible. My thinking was "Click image, identiy what was clicked, store it in a temporary variable holder, and swap with the second (blank) image clicked).
My HTML:
These are the blank images 0-9:
<img src="blank.jpg" id="blank0" onclick="swap()" width="30" height="30"> </button>
<img src="blank.jpg" id="blank1" onclick="swap()" width="30" height="30"> </button>
etc. etc.
These are the numbered images:
<img src="0.jpg" id="0" onclick="" width="30" height="30"> </button>
<img src="1.jpg" id="1" onclick="" width="30" height="30"> </button>
etc.
Try something like this:
(top of all JS):
var holder = '';
var holderId = '';
Then add this to numbered images:
<img src="0.jpg" id="number0" onclick="setHolder(this.src,this.id)" width="30" height="30">
And this to blank:
<img src="blank.jpg" id="blank0" onclick="swapHolder(this)" width="30" height="30">
Then create the two functions like this:
function setHolder(src,id) {
holder = src;
holderId = id;
}
function swapHolder(img) {
img.src = holder;
document.getElementById(holderId).src = 'blank.jpg';
holder = '';
holderId = '';
}
I want to give a bounce animation to each individual hair on mouseover.the animation part is done on the first hair,but i don`t want to give events to each and every hair image.
So here is my question,I am using constructor in my javascript code.Is it possible that I create a method in my prototype and make instances of it? So basiclly I dont want to fire 10 events or 10 addEventListeners,I want a smart way out of this.
How do I complete my task,as in every hair should bounce on mouseover of itself only
My code:
HTML:
<div class="main">
<div class="hair">
<img src="images/single.png" id="hair1" width="13" height="40" >
<img src="images/single.png" id="hair2" width="13" height="40">
<img src="images/single.png" id="hair3" width="13" height="40">
<img src="images/single.png" id="hair4" width="13" height="40">
<img src="images/single.png" id="hair5" width="13" height="40">
<img src="images/single.png" id="hair6" width="13" height="40">
<img src="images/single.png" id="hair7" width="13" height="40">
<img src="images/single.png" id="hair8" width="13" height="40">
<img src="images/single.png" id="hair9" width="13" height="40">
</div>
<div class="face">
<img src="images/ec_logo.png">
</div>
Javascript:
(function(){
hair=function (){
return this;
};
hair.prototype={
bounce:function(){
//code for some bounce animation
}
};
})();
document.getElementById('hair??').addEventListener("mouseover",???,false);????????//this is the part i am confused about,how to give same animation to every single hair by using object instances???
// one event listener for whole 'haircut'
document.getElementsByClassName('hair')[0].addEventListener('mouseover',
function(objEvent)
{
var elImg = objEvent.target;
if (elImg.nodeName == 'IMG')
{
objEvent.stopPropagation();
console.log(elImg.getAttribute('id')); // just for debug
// xxx.bounce(elImg) or whatever you want
}
}, false);
You can delay the bounce using setTimeout:
(function(){
// "private" vars
var delayPace = 100;// ms
var instanceCount = 0;
hair = function (){
// don't need to return this if it's going
// to be instantiated via the new keyword
this.delay = instanceCount * delayPace;
instanceCount++;
};
hair.prototype={
delay : 0,
bounce : function(){
this.stop();
this._t = setTimeout(this._bounce, this.delay);
},
_bounce : function(){
// this is were the actual magic happens
},
stop : function(){
if(this.t){
clearTimeout(this.t);
}
// other code to stop the animation
}
};
})();
// keep all your hairs in one place!
var hairs = [];
// instantiate them
hairs.push(new hair());
//...
hairs.push(new hair());
var onHover = function(){
hairs.forEach(function(h){
h.bounce();
});
}
I have this script:
jQuery(document).ready(function(){
$(".imgSwap").mouseenter(function() {
$(this).src("_off").replaceWith("_on");
}).mouseleave(function() {
$(this).src("_on").replaceWith("_off");
});
});
And this html:
<div id="nav">
<table>
<tr>
<td class="tdleft">
<img src="../../nav/prev_off.png" width="104" height="37" /></td>
<td class="tdcenter">
<img src="../../nav/crumb_on.png" width="30" height="30" alt="Pagina 1" />
<img src="../../nav/crumb_off.png" width="30" height="30" />
<img src="../../nav/crumb_off.png" width="30" height="30" /></td>
<td class="tdright">
<img class="imgSwap" src="../../nav/next_off.png" width="104" height="37" /></td>
</tr>
</table>
</div>
I can not convince my image with class imgSwap to swap on mouseenter or mouseleave.
I think the problem is in the replaceWith-part of the code.
But I don't know how to fix it, and I couldn't find a clear example (clear to me, at least) on Stack Overflow either.
Instead of
$(this).src("_off").replaceWith("_on");
use
this.src = this.src.replace("_off", "_on");
You want to do a replacement in the src string while replaceWith do DOM elements replacements.
You should also probably simplify your code using hover :
$(function(){
$(".imgSwap").hover(function() {
this.src = this.src.replace("_off", "_on");
}, function(){
this.src = this.src.replace("_on", "_off");
});
});
I have the following code to display the images
<ui:repeat id="repeat5" value="#{getData.imageThumbnail1}" var="imagesLst2" varStatus="loop">
<h:panelGroup>
<p:commandLink id="cl3" action="#{getData.imageID(imagesLst2.imageID)}" styleClass="ovr" update=":mainForm:tabView:example">
<p:graphicImage id="gi3" value="#{imagesStreamer.image}" styleClass="bord" alt="image not available3" width="60" height="60" >
<f:param name="id5" value="#{imagesLst2.imageID}" />
</p:graphicImage>
</p:commandLink>
</h:panelGroup>
</ui:repeat>
I have a css file to display border for the p:graphicImage
.bord
{
border-style:solid;
border-width:2px;
border-color:#00FFFF;
}
I can view multiple images, when i select a image it needs to change the border-color for that graphicImage (at any point of time there will be only one selected image), how do i do it in PrimeFaces
I tried using a javascript but could not figure out how to change the border for an existing component.
UPDATE:1
I did the above task with the following code
<p:graphicImage id="gi3" value="#{imagesStreamer.image}" onmousedown="mouseDown(this)" styleClass="bord" alt="image not available3" width="60" height="60" >
and the javascript
function mouseDown(element) {
var element1 = (element);
element1.style.borderColor="#ff0000";
}
Now my problem is how do i change the previously selected border colour on a new selection.
This is how i did the above things
jsf code
<p:graphicImage id="gi3" value="#{imagesStreamer.image}" onmousedown="mouseDown(this)" styleClass="bord" alt="image not available3" width="60" height="60" >
javascript
var elementOld;
function mouseDown(element) {
var element1 = (element);
element1.style.borderColor="#ff0000";
if(elementOld != null){
elementOld.style.borderColor="#739E39"
}
elementOld = element1;
}
Thanks to BalusC reply
How to refer to a JSF component Id in jquery?
I think this is a cleaner solution, and you won't have to use global variables.
Add a that surrounds the ui:repeat. Then simply solved with jquery.
markup:
<p:graphicImage id="gi3" value="#{imagesStreamer.image}" alt="image not available3" width="60" height="60" onclick="setBorder(this)">
javascript:
function setBorder(element) {
$('#imageContainer .bord').removeClass('bord'); // Removes the border from all images that has it.
$(element).addClass('bord'); // Adds the border class to the clicked image.
}