jQuery/JavaScript facebook thumbnail update - javascript

I'm trying to get background-image url and replace with meta og:image property:
function getBackgroundImageUrl($element) {
if (!($element instanceof jQuery)) {
$element = $($element);
}
var imageUrl = $element.css('background-image');
return imageUrl.replace(/(url\(|\))/gi, '');
}
var image = getBackgroundImageUrl(".et_pb_slide.et_pb_bg_layout_dark.et_pb_media_alignment_center.et-pb-active-slide");
$("meta[property='og\\:title']").attr("content", image);
Function properly gets background-image url, but meta tag is still empty.
Any idea?

Related

How can I test if a link is valid in Javascript or JQuery? [duplicate]

This question already has answers here:
How do I check if file exists in jQuery or pure JavaScript?
(19 answers)
Closed 3 years ago.
We are currently developing a web interface (only for viewing) for one of our applications, which is C++ based. The web application uses Bootstrap. I am a JavaScript and JQuery beginner.
At the top of the web page I need to display a thumbnail if it's available, otherwise a default picture.
I have the link to the thumbnail, even if it's not pointing at any resources (the picture can be deleted for different reasons that are irrelevant here, and this is not an error). The link to the thumbnail has the following format /resources/id={some_id}
Using jquery, I do the following :
<html>
<body>
<img id="thumbnail" />
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
/* thumbnailSrc will always contain something valid,
but that can point to some not existing picture */
let thumbnailSrc = jobDescription.thumbnailSrc;
$('#thumbnail').attr("src", thumbnailSrc);
});
</script>
</body>
</html>
If the link is valid, everything is fine; otherwise, it displays a broken picture. I would like to test if thumbnailSrc is a valid link (not returning a 404 error) to be able to do something like:
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
let thumbnailSrc = jobDescription.thumbnailSrc;
if (/* thumbnailSrc link is working */)
$('#thumbnail').attr("src", thumbnailSrc);
else
$('#thumbnail').attr("src", "/resources/default_picture.png");
});
</script>
How can I test in Javascript (or JQuery) if a link is valid?
Use a callback function like below
<img src="image.gif" onerror="myFunction()">
<script>
function myFunction() {
alert('The image could not be loaded.');
}
</script>
You can assign to your image an onerror event, and inside it you can assign to src the fallback source, e.g. in jQuery it would be like this:
$(function() {
$('#thumbnail').on('error', function() {
let fallback_img_src = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
$(this).attr('src', fallback_img_src);
});
let wrong_img_src = 'wrong_img_src.jpg';
$('#thumbnail').attr('src', wrong_img_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="thumbnail" />
The following loads the image and if 404, loads the default:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
el.addEventListener("load", function(ev) {
document.body.appendChild(el);
});
el.addEventListener("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
In jQuery:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
$(el).on("load", function(ev) {
document.body.appendChild(el);
});
$(el).on("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Image src relative path to absolute path

I have website and now making a hybrid app for it.
I get all my blog post using Jquery get method.
However the issue is that <img src="/media/image.png"> is sometime relative url and sometime an absolute url.
Everytime an absolute url breaks the image showing 404 error.
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
Note: I need to change images present only in <div id="details"> div.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
You can use common function or image onload to rerender but I h
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
document.querySelectorAll('#details img').forEach(img => {
const src = img.getAttribute('src');
// use regex, indexOf, includes or whatever to determine you want to replace the src
if (true) {
img.setAttribute('src', 'https://www.example.com' + src);
}
});
The best would be to do this with the response html from the ajax request before inserting into the main document so as to prevent needless 404 requests made while changing the src
Without seeing how you are making your requests or what you do with the response here's a basic example using $.get()
$.get(url, function(data){
var $data = $(data);
$data.find('img[src^="/media/"]').attr('src', function(_,existing){
return 'https://www.example.com' + existing
});
$('#someContainer').append($data)'
})
You can just get all the images from an object and find/change them if they don't have absolute url.
var images = $('img');
for (var i = 0 ; i < images.length ; i++)
{
var imgSrc = images[i].attributes[0].nodeValue;
if (!imgSrc.match('^http'))
{
imgSrc = images[i].currentSrc;
console.info(imgSrc);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/test.jpg">
<img src="/media/test.jpg">
<img src="https://www.example.com/media/test.jpg">

lightbox onclick change src then change back

I am using Materialize CSS and have the "Material Box" which is a lightbox plugin. I want all of the thumbnails to be the same size. When clicked I want the full photo to load.
I am using onclick to change the src. How do I change it back to the thumbnail when the large photo closes (either with a click or the escape key)?
<div class="col s6 m3">
<img class="materialboxed responsive-img" src="images/thumb1.jpg" onclick='this.src="images/photo1"'>
</div>
Material Box Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.materialboxed');
var options = {}
var instances = M.Materialbox.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.materialboxed').materialbox();
});
Materializecss.com - https://materializecss.com/media.html
I haven't found an easy other way of achieving the lightbox effect with cropped square thumbnails. Any advice would be greatly appreciated!
Here is one implementation of what you want, keeping track of the image click state.
$(document).ready(function(){
$('.materialboxed').materialbox();
// Image sources
const srcThumb = '/images/thumb1.jpg'
const srcPhoto = '/images/photo1.jpg'
// Click state
var clicked = false
// Get image element and bind click event
const img = $('.materialboxed')
img.on('click', function() {
img.attr('src', clicked ? srcPhoto : srcThumb)
clicked = !clicked
})
});
No need to rely on onclick in this case.
Materialize is already binding onclick for those images.
And it provides the following native methods we can use for doing exactly what you want using pure JS (no jQuery):
onOpenStart Function null Callback function called before materialbox is opened.
onCloseEnd Function null Callback function called after materialbox is closed.
In this example below, we assume there is a normal materialboxed photo gallery containing thumbnails named thumb_whatever.jpg, for example. But we're also serving the original sized photo named whatever.jpg in the same directory.
Then we're changing src attribute dynamically removing the thumb_ prefix to get the original image, which in this case will be imediately lightboxed by materialize.
And after closing the lightbox, the src attribute is being set back again without the thumb_ prefix.
We do that while initializing Materialbox:
// Initializing Materialbox
const mb = document.querySelectorAll('.materialboxed')
M.Materialbox.init(mb, {
onOpenStart: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('thumb_','') // get the filename and removes 'thumb_' prefix
var newSrc = path+fileName // re-assemble without the 'thumb_' prefix
el.setAttribute('src', newSrc)
},
onCloseEnd: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('/', '/thumb_') // get the filename and adds 'thumb_' prefix
var newSrc = path+fileName // re-assemble with the 'thumb_' prefix
el.setAttribute('src', newSrc)
}
})
This solution is also working like a charm for me, crossplatform.

How can I check if the href path contain image or someother link using javascript or jquery?

Any One Know Tell me the suggestion to do this. How can i check if the anchor href attribute contain image path or some other path.
For Example:
<img src="image.jpg"/>
<img src="image.jpg"/>
See the above example shows href attribute contain different path like first one is the image and second one is the some other site link. I still confuse with that how can i check if the href path contain the image path or some other path using jquery or javascript.
Any suggestion would be great.
For example (you may need to include other pic formats if needed):
$("a").each(function(i, el) {
var href_value = el.href;
if (/\.(jpg|png|gif)$/.test(href_value)) {
console.log(href_value + " is a pic");
} else {
console.log(href_value + " is not a pic");
}
});
Jquery:
$(document).ready( function() {
var checkhref = $('a').attr('href');
var image_check = checkhref.substr(checkhref.length - 4)
http_tag = "http";
image = [".png",".jpg",".bmp"]
if(checkhref.search("http_tag") >= 0){
alert('Http!');
//Do something
}
if($.inArray(image_check, image) > -1){
alert('Image!');
//Do something
}
});
you may check if image exists or not, without jQuery
Fiddle
var imagesrc = 'http://domain.com/image.jpg';
function checkImage(src) {
var img = new Image();
img.onload = function() {
document.getElementById("iddiv").innerHTML = src +" exists";
};
img.onerror = function() {
document.getElementById("iddiv").innerHTML = src +"does not exists";
};
img.src = src; // fires off loading of image
return src;
}
checkImage(imagesrc);

How to detect dimensions of file using File API and Dropzone.js

Using Dropzone.js, I need to detect the dimesions of the image when added files and apply them to its parent .details div. The following code code works and return an alert with the added image width.
myDropzone.on("addedfile", function(file, xhr) {
var fr;
fr = new FileReader;
fr.onload = function() {
var img;
img = new Image;
img.onload = function() {
return alert(img.width);
};
return img.src = fr.result;
};
return fr.readAsDataURL(file);
});
The thing is that I have no idea how to assign the width to its parent .details element which set the preview width of the preview.
I try replacing the alert for this code but it doesn't do anything.
$(this).parent('.details').css('height',img.height);
I'm a bit lost in how to relate the value inside the onload function to applying it to its parent class.
With the latest version of dropzone you don't have to write this code yourself.
Simply read the file.width and file.height properties that are set on the file object when the thumbnail is generated.
The problem, why your CSS doesn't affect the element, is because you didn't specify the unit, px in this case. So your code can be:
myDropzone.on("thumbnail", function(file) {
$(this.element).parent('.details').css('height', file.height + 'px');
});

Categories