I'm working on a web site that shows random articles in the footer.
Random articles should be 4 and these articles should not be duplicated.
How to make a loop through arrays to make it work.
Here is the code and fiddle for one article I made. Thanks!
FIDDLE: https://jsfiddle.net/3db8Leor/1/
HTML:
<section class="cities">
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<!--
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
-->
</section>
JS:
const link = [
'https://www.croatiaweek.com',
'https://www.pinebeach.hr/',
'https://www.dnevnik.hr/',
'https://www.costacruises.com/',
'https://www.zadar.hr/',
'https://www.croatia.hr/'
];
const title = [
'Zagreb - Croatia',
'Pakostane - Croatia',
'Hvar - Croatia',
'Dubrovnik - Croatia',
'Zadar - Croatia',
'Brac - Croatia'
];
const image = [
'https://www.croatiaweek.com/wp-content/uploads/2015/02/KingTomislav.jpg',
'https://www.pinebeach.hr/photos/modul_2/18052017224635_pine-beach-pakostane-0020.jpg',
'https://image.dnevnik.hr/media/images/920x695/Jul2019/61719533.jpg',
'https://www.costacruises.com/content/dam/costa/inventory-assets/ports/DBV/24-DUBROVNIK_2880x1536.jpg.image.750.563.low.jpg',
'https://www.hdz-zadar.hr/public/img/home/3_mobile.png',
'https://s27135.pcdn.co/wp-content/uploads/2019/06/Brac-island-878x585.jpg.optimal.jpg'
];
const random = Math.floor(Math.random() * title.length);
const city = document.querySelector('.city');
city.href = link[random];
city.querySelector('h2').innerHTML = title[random];
city.querySelector('img').src = image[random];
You can first generate an array of unique random numbers, then in each loop you can use the index to set the images like the following way:
const link = [
'https://www.croatiaweek.com',
'https://www.pinebeach.hr/',
'https://www.dnevnik.hr/',
'https://www.costacruises.com/',
'https://www.zadar.hr/',
'https://www.croatia.hr/'
];
const title = [
'Zagreb - Croatia',
'Pakostane - Croatia',
'Hvar - Croatia',
'Dubrovnik - Croatia',
'Zadar - Croatia',
'Brac - Croatia'
];
const image = [
'https://www.croatiaweek.com/wp-content/uploads/2015/02/KingTomislav.jpg',
'https://www.pinebeach.hr/photos/modul_2/18052017224635_pine-beach-pakostane-0020.jpg',
'https://image.dnevnik.hr/media/images/920x695/Jul2019/61719533.jpg',
'https://www.costacruises.com/content/dam/costa/inventory-assets/ports/DBV/24-DUBROVNIK_2880x1536.jpg.image.750.563.low.jpg',
'https://www.hdz-zadar.hr/public/img/home/3_mobile.png',
'https://s27135.pcdn.co/wp-content/uploads/2019/06/Brac-island-878x585.jpg.optimal.jpg'
];
const city = document.querySelectorAll('.city');
var arr = [];
while(arr.length < city.length){
var r = Math.floor(Math.random() * title.length);
if(arr.indexOf(r) === -1) arr.push(r);
}
city.forEach(function(c, i){
c.href = link[arr[i]];
c.querySelector('h2').innerHTML = title[arr[i]];
c.querySelector('img').src = image[arr[i]];
});
<section class="cities">
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
<a class="city" target="_blank">
<img src="" width="200">
<h2></h2>
</a>
</section>
Since this is a very simple use case where you only need 4 random indices, you can do something like this jsfiddle (updated yours):
https://jsfiddle.net/fceLu5mq/
Basically:
function pickFour(max) {
const indices = [];
while (indices.length < 4) {
const nextRand = Math.floor(Math.random()*max);
if (!indices.includes(nextRand)) {
indices.push(nextRand);
}
}
return indices;
}
Related
Please I want to hide <a> that contains a link sabdel.com .
I used the below javascript code but it doesn't work
window.addEventListener=()=>{
var elem=document.querySelectorAll("a");
var i;
for(i=0;i<elem.length;i++){
var obj=elem[i];
if(obj.innerHTML.toString().includes('sabdel.com')){
obj.style.display="none";
}
}
}
<div>
<div>
<div>
<div>
<img src="//ae01.alicdn.com/kf/Haabbc1065ea449668ced4bf88021f4aea.png">
<p></p>
<div style="margin-left:36.847599164927%;margin-top:-30.27139874739%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000105891117.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:57.306889352818%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000147845779.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:77.76617954071%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000990281325.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-top:0.31315240083507%;height:0;width:0"></div>
</div>
<div>
<img src="//ae01.alicdn.com/kf/H69979517a8a248e9a84aec8986854e277.png">
<p></p>
<div style="margin-left:1.5657620041754%;margin-top:-31.524008350731%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000985761425.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:26.096033402923%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000224026872.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:50.62630480167%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/1005001597400364.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:75.156576200418%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4001044974112.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-top:0.73068893528184%;height:0;width:0"></div>
</div>
First of all, you are incorrectly using addEventListener. Second, you must check the href attribute, not innerHTML:
window.addEventListener("yourEvent", () => {
var elem=document.querySelectorAll("a");
for(var i = 0; i < elem.length; i++) {
if(elem[i].href.includes('sabdel.com')) {
elem[i].style.display="none";
}
}
}
Replace yourEvent with the event you want to listen with. For example, if you are listening for a click event, replace it with click.
Do you mean like this ?
window.addEventListener = () => {
var tags = document.getElementsByTagName("a");
for (var i = 0; i < tags.length; i++) {
var attributeValue = tags[i].getAttribute('href');
if (attributeValue.includes('sabdel.com')) {
tags[i].style.display = 'none';
}
}
}
I need to get all img src from the class "photo-grid-item".
<a href="/photo/CIJXEU9VRY" class="photo-grid-item">
<img src="someimage.jpg" width="420" height="280" alt="man woman">
</a>
<a href="/photo/125255" class="photo-grid-item">
<img src="another.jpg" width="420" height="280" alt="man woman">
</a>
I have tried
Array.from(document.querySelectorAll(".photo-grid-item")).filter(el=>el.nextElementSibling.src)
What I need is
[someimage.jpg,another.jpg]
const resultArray = [];
const photoGridItems = document.querySelectorAll('.photo-grid-item');
photoGridItems.forEach(photoGridItem => {
let photoGridItemImage = photoGridItem.querySelector('img');
resultArray.push(photoGridItemImage.src)
})
console.log(resultArray)
<a href="/photo/CIJXEU9VRY" class="photo-grid-item">
<img src="someimage.jpg" width="420" height="280" alt="man woman">
</a>
<a href="/photo/125255" class="photo-grid-item">
<img src="another.jpg" width="420" height="280" alt="man woman">
</a>
hello friends i am trying to get the size (height and width) of an image from an hrf and put these values in its attribute
This is driving me crazy
this is my html:
<figure>
<a href="image-large-1.jpg">
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg">
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg">
<img src="image-small-3.jpg"/>
</a>
</figure>
this is what I want :
<figure>
<a href="image-large-1.jpg" original-size="1000x800"> //the sizes are example
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg" original-size="1200x700"> //the sizes are example
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg" original-size="900x980"> //the sizes are example
<img src="image-small-3.jpg"/>
</a>
</figure>
the "original-size" attribute I want to get it from " a hrf "
I was trying with this code that I found here, I get the original size of the image-large from the href (in the console.log) but I cannot print them in the html
help me please
$(".containerGallery figure a").each(function() {
var imgSrc, imgW, imgH;
function myFunction(image){
var img = new Image();
img.src = image;
img.onload = function() {
return {
src:image,
width:this.width,
height:this.height};
}
return img;
}
var x = myFunction($(this).attr('href'));
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
$(this).each(function() {
x.addEventListener('load',function(){
console.log(imgW+'x'+imgH);
$(this).attr('original-size', imgW+'x'+imgH);
});
});
});
The JavaScript code in the question is overly complex and redundant.
Here's some simplified code that accomplishes the same thing.
// get all <a> elements inside <figure> elements
const atags = Array.from(document.querySelectorAll('figure a'));
// iterate over every <a> tag
atags.forEach(atag => {
// create blank image element
var img = new Image();
// when the image loads, store its dimensions to the atag's
// `data-original-size` attribute
img.addEventListener('load', () => {
let imgW = img.width,
imgH = img.height;
atag.dataset.originalSize = `${imgW}x${imgH}`;
console.log('atag:', atag);
});
// load image from atag's href
img.src = atag.href;
});
<figure>
<a href="https://i.picsum.photos/id/1077/200/300.jpg">
<img src="https://via.placeholder.com/40" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/913/200/200.jpg">
<img src="https://via.placeholder.com/50" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/1058/100/100.jpg">
<img src="https://via.placeholder.com/60" />
</a>
</figure>
Here is script that does absolutely what you're looking for!
const getOriginalSize = (target, url) => {
const image = document.createElement("img");
image.src = url;
image.onload = function(){
target.setAttribute("original-size", `${image.naturalWidth}x${image.naturalHeight}`);
}
return image;
}
<figure>
<a href="https://images.sftcdn.net/images/t_app-cover-l,f_auto/p/befbcde0-9b36-11e6-95b9-00163ed833e7/260663710/the-test-fun-for-friends-screenshot.jpg">
<img src="https://images.sftcdn.net/images/t_app-cover-l,f_auto/p/befbcde0-9b36-11e6-95b9-00163ed833e7/260663710/the-test-fun-for-friends-screenshot.jpg"/>
</a>
</figure>
<figure>
<a href="https://www.velior.ru/wp-content/uploads/2009/05/Test-Computer-Key-by-Stuart-Miles.jpg">
<img src="https://www.velior.ru/wp-content/uploads/2009/05/Test-Computer-Key-by-Stuart-Miles.jpg"/>
</a>
</figure>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll("figure").forEach( (figure) => {
figure.querySelectorAll("a[href]").forEach( function(targetAhref) {
getOriginalSize(targetAhref, targetAhref.href);
console.warn("image loaded and size registred!");
} );
} );
} );
</script>
I have a list of elements which contains an image & few more elements. I need to get the src of the image. HTML code is like this.
<div class="flex-card">
<div class="flex-figure">
<a href="">
<figure class="image">
<span class="fig-lable">Colombo</span>
<img src="https://wenuka.com/media/visit-fl/banner-img.jpg" class="tile-media"/>
</figure>
</a>
</div>
</div>
I tried to get the src of the image with this code.
var elem = document.getElementsByClassName("flex-figure");
for (var i = 0; i <= elem.length; i++) {
var imgTag = elem[i].getElementsByTagName('img')[0];
var srcLink = imgTag.src;
console.log(srcLink);
}
It gives the following error.
Uncaught TypeError: Cannot read property 'src' of undefined
You have an off-by-one error, but why not use querySelectorAll instead, it'll be a lot cleaner:
const imgs = document.querySelectorAll('.flex-figure img');
imgs.forEach(img => console.log(img.src));
<div class="flex-card">
<div class="flex-figure">
<a href="">
<figure class="image">
<span class="fig-lable">Colombo</span>
<img src="https://wenuka.com/media/visit-fl/banner-img.jpg" class="tile-media"/>
</figure>
</a>
</div>
</div>
querySelectorAll is a lot more flexible than the getElementsBy* methods, and also returns a static NodeList which can be directly iterated over, unlike the other methods (which return live HTMLCollections, which can be difficult to deal with).
Change
for (var i = 0; i <= elem.length; i++) {
To
for (var i = 0; i < elem.length; i++) {
var elem = document.getElementsByClassName("flex-figure");
for (var i = 0; i < elem.length; i++) {
var imgTag = elem[i].getElementsByTagName('img')[0];
var srcLink = imgTag.src;
console.log(srcLink);
}
<div class="flex-card">
<div class="flex-figure">
<a href="">
<figure class="image">
<span class="fig-lable">Colombo</span>
<img src="https://wenuka.com/media/visit-fl/banner-img.jpg" class="tile-media"/>
</figure>
</a>
</div>
</div>
console.log(document.getElementsByTagName("IMG")[0].src)
<div class="flex-card">
<div class="flex-figure">
<a href="">
<figure class="image">
<span class="fig-lable">Colombo</span>
<img src="https://wenuka.com/media/visit-fl/banner-img.jpg" class="tile-media"/>
</figure>
</a>
</div>
</div>
I have a script, the goal of which is to sort a list of entire div classes (containing images) in ascending order as determined by a number within that div class. It has to work at the push of a button. It works relatively well, except it keeps sorting the items by the first digit rather than the number as a whole (resulting in an arrangement like 1, 10, 11, 2, 3, etc.)
My entire code is below, please show me how to fix this.
NOTE: I am looking for any possible solution but if it's possible to keep the script close to its current form I would prefer that
CSS:
.number{
display:block;
color:black;
font-size:30px;
margin:20px
}
HTML:
<div id="sortingbutton">
<button>Sorting Button</button>
</div>
</div>
<ul id="list">
<li>
<div class="number">5</div>
<img src="http://i.imgur.com/b70bLk1.png" width="250px" height="250px" alt="aqua" />
</li>
<li>
<div class="number">4</div>
<img src="http://i.imgur.com/keE5Thi.png" width="250px" height="250px" alt="tan" />
</li>
<li>
<div class="number">1</div>
<img src="http://i.imgur.com/EgqCTZJ.png" width="250px" height="250px" alt="black" />
</li>
<li>
<div class="number">3</div>
<img src="http://i.imgur.com/4onkGsz.png" width="250px" height="250px" alt="grey" />
</li>
<li>
<div class="number">9</div>
<img src="http://i.imgur.com/To88ZFN.png" width="250px" height="250px" alt="orange" />
</li>
<li>
<div class="number">2</div>
<img src="http://i.imgur.com/6ZtB1VW.png" width="250px" height="250px" alt="purple" />
</li>
<li>
<div class="number">6</div>
<img src="http://i.imgur.com/5Pz2Q2Y.png" width="250px" height="250px" alt="yellow" />
</li>
<li>
<div class="number">7</div>
<img src="http://i.imgur.com/VqAdV1K.png" width="250px" height="250px" alt="blue" />
</li>
<li>
<div class="number">8</div>
<img src="http://i.imgur.com/4HCxTpm.png" width="250px" height="250px" alt="green" />
</li>
<li>
<div class="number">10</div>
<img src="http://i.imgur.com/JjjHmM0.png" width="250px" height="250px" alt="pink" />
</li>
<li>
<div class="number">11</div>
<img src="http://i.imgur.com/EpB8YgU.png" width="250px" height="250px" alt="Red" />
</li>
</ul>
Javascript:
window.onload = function () {
var desc = false;
document.getElementById("sortingbutton").onclick = function () {
sortUnorderedList("list", desc);
desc = !desc;
return false;
}
}
function compareText(a1, a2) {
var t1 = a1.innerText,
t2 = a2.innerText;
return t1 > t2 ? 1 : (t1 < t2 ? -1 : 0);
}
function sortUnorderedList(ul, sortDescending) {
if (typeof ul == "string") {
ul = document.getElementById(ul);
}
var lis = ul.getElementsByTagName("LI");
var vals = [];
for (var i = 0, l = lis.length; i < l; i++) {
vals.push(lis[i]);
}
vals.sort(compareText);
if (sortDescending) {
vals.reverse();
}
ul.innerHTML = '';
for (var i = 0, l = vals.length; i < l; i++) {
ul.appendChild(vals[i]);
}
}
Why not just use a1.innerText - a2.innerText in compareText?
Explanation
When you compare two strings using less and greater than symbols javascript doesn't convert them to integers, as javascript can compare two strings, no problem. For example "10" > "2" returns true, cause "10" is longer.
However when you use subtraction operator javascript can't subtract strings so it converts it into integers.
Use parseInt to convert string variables into integers.
http://www.w3schools.com/jsref/jsref_parseint.asp
Sorting by first digit is string sorting.
for (var i = 0, l = lis.length; i < l; i++) {
vals.push(parseInt(lis[i], 10));
}