trying to grab image url within div's children - javascript

I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."

You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");

Related

How to make a photo appear when clicking on another photo? Javascript, DOM

I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.

Can't add button under div

I have a Chrome extension that inserts a button onto HTML pages. I got it to add the button under one div. Now I'm trying to get it to add it under an image in that div, and it won't work — no errors, the button just doesn't appear. When I do console.log(image_div); it prints out the image object.
Version that works:
var uCW = jNode.closest("[role='article']");
uCW.append(button);
Version that doesn't work:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.append(button);
uCW is the variable name I gave to the parent div, and image_div is the variable name I gave to the child within uCW that contains the image.
The problem that you are having is you are appending to a div successfully, but appending to an image is failing. The reason is you can't append to an image, you have to use 'after' since an image isn't an object that can content appended to the innerHTML of it.
So change this:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.append(button);
to:
var image_div = $(uCW).find('[src^="https://external"]');
image_div.after(button);

Find an element by tag using angularjs

Requirement Description:
I have a page in which there is a description section. The description section is basically a big html section consists of images and texts.
So if a user clicks on an image, then the user should be redirected to another page which has only the description data in it. After redirection, the page should scroll itself to that clicked image.
Standard Solution
I know the issue is easy if we have the id for each image, such that we can send the id in the url with the hash and then using $anchorscroll, the page will automatically scrolls to that clicked image.
Actual Problem
But the issue is that i dont have an id with the img tag.
The html of description section is like this:
....
<div class="someclass"><img src="cdn url of the image"></div>
....
Please note that there is no such particular format of the html structure.
It can be in any form.
But the img tag contains only src.
The other page also has the same description data and HTML structure as the previous. I just need to scroll the page to the clicked image.
What can be the solution?
It's not good practises to do such things with AngularJS.
Anyway, I made you a function that will search for images that only contain src attributes.
But be carefull, if you remove or manipulate the elements, remember to call the $scope.$apply() Method! Otherwise AngularJS will not know that any element has been changed.
/**
* Gets all images with only a src attribute
* #param element Any element from where to start the function. If not defined document will be used
* #returns {Array} An array of Matching element
*/
function getMyImages(element) {
element = element || document;
var images = element.querySelectorAll('img[src]');//Get all images with src attributes
var matches = [];
for (var i = 0, j = images.length; i < j; i++) {
var attributes = images[i].attributes;
if (attributes.length > 1) {//Skip images with more than one attribute
continue;
}
if (attributes[0].name === 'src') {//if the attribute is a src attribute, add it to the matches
matches.push(images[i]);
}
}
return matches;//Matches will now just contain images with only src attribute
}

Preloading and changing images with JavaScript

I'm trying to make some basic image slider as a part of JS excersises, and I've noticed something weird when I ran this script.
The source of an image stored in array under the 0 index is changing when I'm trying to change source image in html code with 'setAttribute' method, so when I want to get back from fifth image to one, this proto-slider (nothing is sliding at the moment) is stuck at second image.
My files are named 0.jpg - 5.jpg.
I've preloaded the images to be displayed smoothly without flicker and I'm displaying one image after the page loads, and then I'm trying to change source of this image to source of next image in array of images. Is this the right way to do it?
Here's the code:
var images = new Array(5);
var i=0;
function addImages(){
for (var j=0;j<images.length;j++){
images[j] = new Image();
images[j].src = j+".jpg";
console.log(images[j].src);
}
var article = document.getElementById("article");
article.insertBefore(images[0], document.getElementById("nav"));
}
function next(){
if (i<images.length-1){
document.getElementsByTagName('img')[0].setAttribute('src',images[++i].src);
console.log(images[0].src);
}}
function prev(){
if (i>0){
document.getElementsByTagName('img')[0].setAttribute('src', images[--i].src);
console.log(images[0].src);
}
}
What is the best way to do such a this as dynamically changing image sources?
I've thought about this:
article.removeChild(document.getElementsByTagName("img")[0]);
article.insertBefore(images[++i], document.getElementById("nav"));
I want to know if this isn't considered as a bad practice and what are the other ways to do it in single line of code.
Thanks in advance and sorry for grammar mistakes.
You could just insert empty image
<img id="someid">
and then use document.getElementById("someid").src=images[0].src
If you'd like to be sure that images[0] is completely loaded, use onload function, like:
images[0].onload=function()
{
document.getElementById("someid").src=images[0].src;
}

Thumbnail gallery that loads image description and full size on same page on click

I want to create something like this.
Where do I get started with the javascript? Also, is it possible to customize something like this with the Nextgen Gallery plugin or another Wordpress plugin?
You will need two things:
A data Object that maps the thumbnail src value (or any other identifer) to the required URL and description Strings.
Some Event handler for the thumbnails that get the respective entries in the data Object and set the highlight img Node's src attribute as well as the description text.
So, let's say this is your data Object:
var data = {
<src>: {
"url": <url for the large image> ,
"text": <description for the large image>
} ,
<another src>: {
//..
}
}
Now, you just have to get the src of the thumbnail img Node that raised the Event and get its respective entry in the data Object,
var img = /* the reference to the img Node that raised the event */ ;
var src = img.getAttribute("src") ;
var entry = data[src] ;
var url = entry.url , text = url.text ;
; then you simply have to change the src attribute of the large img Node and the text content of the Node containing the description.
You could also do the same thing using the id attribute.
HTH

Categories