I have an array of image links that I'm getting from reddit, but some image urls are broken. I want to skip over broken image links.
This thread suggested using .width to see if an image exists. I tried using this answer to wait for image links to load before executing code but it's not working, it's skipping right over my if(this.width>0) check.
var imgLinksArray = Array.from(imgLinks);
document.getElementById('photoGrid').innerHTML = "";
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
var img = new Image();
img.onload = function() {
console.log(this);
console.log(this.src + " Width: " + this.width);
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
if (this.width > 0) {
console.log(this.width);
if (workingImgLink.search("webm") >= 0) {
document.getElementById('photoGrid').innerHTML += '<video autoplay loop class="box-wrapper"> <source type="video/webm" src= "' + workingImgLink + '" data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></video>';
} else {
document.getElementById('photoGrid').innerHTML += '<div class="box-wrapper"> <div data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></div></div>';
}
}
}
}
img.src = workingImgLink;
var bgImgWidth = img.width;
var bgImgHeight = img.height;
}
I only want to execute the innerHTML code if I know the image exists. Any suggestions about how to go about this?
Related
Im trying to change the cursor logo when Im building a dynamic div. Depending on how much data it can take up a few seconds to load so I need the cursor change.
The problem Im having is that the cursor isnt changing until my code has fully executed.
Im have a dynamically generated chart with the points in the chart set to popup more data when they are clicked. This is the eventListener Ive created and it works fine apart from my CSS update not getting applied until it has exited the function.
Any idea how I can force it to update immediately
point.addEventListener('click', function (evt) {
document.body.className = 'waiting';
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
// pop up
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
//document.body.style.cursor='default';
txnsPerMinutePopUp.style.visibility = 'visible';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}, false);
My CSS then is just
body.waiting * { cursor: wait; }
UPDATE
From researching potential causes I found out that most browsers wont update the DOM immediately and I need to interrupt the javascript to allow for the DOM to get updated.
Ive updated my code to move the bulk of the operations out to a separate function and tried to set a timeout value on it and its still not updating the cursor until everything completes.
I also tried to add a mousedown event to try and get ahead of the javascript in the on click but it didnt work either
EventListener
point.addEventListener('click', function (evt) {
//document.body.className = 'waiting';
// setTimeout(function() {
Charts.lineChart.changeCursor();
// },10);
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
setTimeout(function() {
Charts.lineChart.breakOut( txnFullData,theDate );
},100);
document.body.style.cursor='default';
txnsPerMinuteTweetsPopUp.style.visibility = 'visible';
}, false);
and the following code was moved into the breakout function
breakOut
Charts.lineChart.breakOut = function(txnFullData,theDate){
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}
I'm trying to tweak some code I found online to create an expand button beside a web part in a Sharepoint site. The issue with this code is that the default is that all web parts are already expanded, and you would have to click to collapse it. I would only like to have my FAQ (WebPartWPQ7) web part already collapsed, and users can expand it with a click. The other web parts do not need an expand/collapse button.
<script type="text/javascript">
//
// Expand/Collapse Buttons
//
function WPToggle(thisId, ImageId) {
if (document.getElementById(thisId).style.display == "none") {
document.getElementById(thisId).style.display = "";
document.getElementById(ImageId).src = "/_layouts/images/minus.gif";
} else {
document.getElementById(thisId).style.display = "none";
document.getElementById(ImageId).src = "/_layouts/images/plus.gif";
}
}
function ExpandCollapseBody() {
var i = 1;
var WPid = "WebPartWPQ1";
var WPtitleid = "WebPartTitleWPQ1";
var Toggleid = "ToggleImage1";
do {
try {
document.getElementById(WPtitleid).innerHTML = '<IMG id="' + Toggleid + '" onClick="WPToggle(\'' + WPid + '\',\'' + Toggleid + '\')" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />' + document.getElementById(WPtitleid).innerHTML;
if (document.getElementById(WPid).style.display == "none") {
document.getElementById(Toggleid).src = "/_layouts/images/plus.gif";
}
} catch (err) {}
i = i + 1;
WPid = "WebPartWPQ" + i;
WPtitleid = "WebPartTitleWPQ" + i;
Toggleid = "ToggleImage" + i;
} while (document.getElementById(WPid))
}
_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");
</script>
If you would like to hide the 7th web part, just add a if (i == 7) WPToggle(WPid, ToggleId); to the initialization function. Slightly adapted your code with jquery as you tagged your question as such I assume you can use it:
function WPToggle(thisId, ImageId) {
var isVisible = $('#' + thisId).is(':visible');
$('#' + thisId).toggle(!isVisible);
var img = isVisible ? 'plus' : 'minus';
$('#' + ImageId).attr('src', '/_layouts/images/' + img + '.gif');
}
function ExpandCollapseBody() {
var i = 1;
do {
var WPid = 'WebPartWPQ' + i;
var WPtitleid = 'WebPartTitleWPQ' + i;
var Toggleid = 'ToggleImage' + i;
var htmlImg = '<img id="' + Toggleid + '" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />';
var wpTitle = $('#' + WPtitleid).data('idx', i);
wpTitle
.html(htmlImg + wpTitle.html())
.click(function() {
var idx = $(this).data('idx');
WPToggle('WebPartWPQ' + idx, 'ToggleImage' + idx);
});
if (i == 7) WPToggle(WPid, Toggleid);
i++;
} while ($('#WebPartWPQ' + i).length == 1)
}
_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");
I getting the error "Attribute buttonindex not allowed on element a at this point". My code is
<p><a class="btn btn-success_ar hidden-xs" id="indexCarouselBeforeBtn2" buttonindex="2" role="button">HOVER HERE TO SEE BEFORE</a></p>
and my Script is
<script type="text/javascript" >
var imageList = [];
$(document).ready(function(){
var totalSlides = 5;
for (var i = 1; i <= totalSlides; i++) {
imageList[i] = [];
imageList[i][0] = $('<img />').attr('src', 'after/images/external/index' + i + 'after.jpg').attr('id', 'indexCarouselImg' + i);
imageList[i][1] = $('<img />').attr('src', 'after/images/external/index' + i + 'before.jpg').attr('id', 'indexCarouselImg' + i);
$("#indexCarouselBeforeBtn" + i).mouseenter(function(){
$("#indexCarouselImg" + $(this).attr('buttonindex')).remove();
$("#item" + $(this).attr('buttonindex')).append(imageList[$(this).attr('buttonindex')][1]);
$(this).addClass('btnHover');
});
$("#indexCarouselBeforeBtn" + i).mouseleave(function(){
$("#indexCarouselImg" + $(this).attr('buttonindex')).remove();
$("#item" + $(this).attr('buttonindex')).append(imageList[$(this).attr('buttonindex')][0]);
$(this).removeClass('btnHover');
});
$("#indexCarouselImg" + i).remove();
$("#item" + i).append(imageList[i][0]);
}
});
The error still exists even using P and Div tags instead of the a tag . How can I fix this.
I think that's attribute not exists in HTML.
You can use tabindex.
https://www.w3schools.com/tags/att_global_tabindex.asp
I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.
I am trying to display preloaded images in a newly created popup window. Here is the code:
HTML
<div id="hiddenImages" style="display: none;"></div>
<img src="SmallImage1.gif" width="196" height="130" border="0">
<img src="SmallImage2.gif" width="196" height="130" border="0">
JS
<script type="text/javascript">
preloadImages('BigImage1.png','BigImage2.png');
</script>
// PreLoadImages:
function preloadImages() {
var hiddenDiv = document.getElementById('hiddenImages');
var i;
var img;
for(i = 0; i < arguments.length; i++) {
img = document.createElement('img');
img.src = arguments[i];
img.id = arguments[i];
img.alt = '';
hiddenDiv.appendChild(img);
}
}
// OpenImage:
function OpenImage(element,e)
{
e.preventDefault();
var big_image = element.getAttribute("href");
var img = document.getElementById(big_image);
var top = (screen.height/2)-(img.height/2);
var left = (screen.width/2)-(img.width/2);
var str = "\"" + "width=" + img.width + ",height=" + img.height + ",top=" + top + ",left=" + left + ",status=0, scrollbars=0, resizable=0" + "\"";
alert(str);
var myWindow = window.open(img.src , "win1", str);
}
When I output 'str' variable in OpenImage() function, this code gives perfect dimensions of the big image. However, the size of popup window is always different than size of the image. IE stretches the popup window horizontally while Google Chrome stretches it vertically. In spite of the fact that both browsers show exactly the same dimensions for the image. And these dimensions of the image are actually being set as size of the pop up window.
Regards.
Try this out, also try to rename your variable top, I think javascript read this as a keyword.
var str = "width=" + img.width + ",height=" + img.height + ",top=" + tops + ",left=" + left + ",status=0, scrollbars=0, resizable=0 ";