I have a lightbox which is getting the background image of another div and then stripping the url() to then put the link inside of an which is working in all browsers except Firefox and can't work out why this would be happening, in Firefox for me it is adding '' around the "" within the src which is breaking the link.
_getImagePath: function($el) {
var imagePath,
spanEl = $el.find('span.js-cell-image-background'),
imgEl = $el.find('img.cell-image__image');
if(spanEl.length) {
imagePath = spanEl.css('backgroundImage');
imagePath = imagePath.replace('url(', '').replace(')', '');
} else if(imgEl.length) {
imagePath = imgEl.attr('src');
}
return imagePath;
},
Just remove the "" as you do the brackets:
imagePath = imagePath.replace('url(', '')
.replace(')', '')
.replace(/^"/, '')
.replace(/"$/, '')
or in one:
imagePath = imagePath.replace(/^url\(\"?/, '').replace(/\"?\)$/, '')
As you've found, the backgroundImage property is browser-dependent. As an example, I have a site, opened in 3x browsers, opened console and typed:
$(".icon-home").css("backgroundImage")
Chrome:
"url(http://..url../images/home.png)"
Firefox:
"url("http://..url../images/home.png")"
IE10:
"url("http://..url../images/home.png")"
Thank you for the reply freedomn-m I managed to solve this a few minutes before you posted by just changing this line:
imagePath = imagePath.replace('url(', '').replace(')', '');
To this:
imagePath = imagePath.replace(/url\(["]*/,'').replace(/["]*\)/,'');
Thanks,
Luke.
Related
$("a > img").each(function () {
if ($(this).attr("alt") == undefined || $(this).attr("alt") == "") {
var name = $(this).attr('src');
name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to get all images inside a link that don't have an ALT tag. Then get the image name as a string and add it as ALT tag to the image. Everything works fine except for the regular expression. Right now it's adding the image path as an ALT which doesn't fix my ADA issues.
The reason i am doing that is because i am trying to fix the ADA issues on the website. (Every image inside a link must have an alt tag)
You need to reassign the updated value after replace to name variable again and then update the image alt attribute like:
name = name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
// If a link has an image and no aria label
//Get image source, strip everything except for image name
//Add image name as aria-label to the link
$('a:has(> img)').each(function () {
var URL = $(this).children('img').prop('src');
var output = URL.split('/').pop();
output = output.replace(/[- .\s]/g, " ");
$(this).attr('aria-label', output);
});
I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}
I have a problem with some javascript in Internet Explorer.
It works fine in other browsers.
I have the following method, that changes the src property of an images and when this happens a download of that image should start. See below:
for (var i = 0; i < imagesStartedDownloading.length; i++) {
if (imagesStartedDownloading[i] == false && responseItems[i] == true) {
console.log("image", i);
var url = baseurl + "/ImageDownload/?imageName=" + hash + "_" + imageDegrees[i] + ".jpg" + "&r=" + Math.random();
imagesStartedDownloading[i] = true;
images.eq(i).attr("src", url);
}
}
The problem is that in when changing this property Internet Explorer starts an endless loop of downloading images. Notice that i have put a console.log in the for-loop. I can confirm that this for-loop does not run in an endles loop. It is only run once for each image that should be downloaded. So that is not the problem.
The behaviour can actually be seen on this page: http://www.energy-frames.dk/Konfigurator. Hit F12 and check in the network tab. Make a change to image on the homepage so a download of new images is started, e.g. Bredde(Width in english), see below:
When this change is made new images are downloaded in an endless loop(it happens almost every time in IE). See below of what you could change
I have really spent a lot of time debugging in this and i cant see why it behaves like this in IE but not in all other browsers.
So does anyone have any idea why this happens? Or have some suggestions on what i could try?
EDIT:
#gxoptg
I have tried what you suggested. using "javascript:void 0" like this:
var newimg = $("<img class='rotator" + (isMainImage ? " active" : "") + "' src='javascript:void 0' />");
and this:
img.attr("src", "javascript:void 0");
gives me this error:
On the other hand, if i completely remove the line img.attr("src", "");
in the imgLoadError method, then i see that images are not downloaded in an endless loop. On the other hand they are not displayed. So am i using the javascript:void 0 wrong?
When i do the following:
img.attr("src", "void(0)");
Then the there is not endless loop but the image wont appear in IE - still works fine in chrome.
Here’s the reason:
for (var i = 0; i < totalnumberofimages; i++) {
var url = "";
var isMainImage = i == currentDragImg;
var newimg = $("<img class='rotator" + (isMainImage ? " active" : "") + "' src='' />");
newimg.on("error", imgLoadError);
newimg.on("load", imgLoaded);
imgcontainer.append(newimg);
}
Note the var newimg = $(...) line. In Internet Explorer, setting an empty src attribute on an image triggers the error event. Due to the error, the imgLoadError function is called. It looks like this:
function imgLoadError(e) {
var img = $(e.currentTarget);
var imgSrc = img.attr("src");
if (imgSrc.length > 0 && img.width() <= 100) {
setTimeout(function () {
var imgUrl = img.attr("src");
img.attr("src", "");
img.attr("src", imgUrl);
}, 200);
}
}
In this function, you run img.attr("src", ""), which sets the empty src attribute, triggers the error event, and calls imgLoadError function again. This causes the endless loop.
To prevent the error (and therefore the endless loop), set image source to "javascript:void 0" instead of "" in both code pieces. This source is valid and should work properly.
(According to comments, all the code is located in /Assets/Scripts/directives/image.rotation.directive.js file.)
An alternative solution is to set the src attribute to a valid, minimal, Base64 encoded image, as in http://jsfiddle.net/leonardobraga/1gefL8L5/
This would avoid triggering the endless error handling and it doesn't impact the code size that much.
I'm creating a small plugin that takes the href value of hyperlinks to pages on YouTube, Vimeo, DailyMotion and KickStarter and then convert it to the embeded URL to display in an iframe within a lightbox.
Of course, the reason why I'm here is I'm having a bit of trouble getting it to work properly! These are the possible links that it can accept:
http://www.youtube.com/watch?v=[token]
http://www.youtu.be/[token]
http://www.vimeo.com/[token]
http://www.dailymotion.com/video/[token]
http://www.kickstarter.com/projects/[token]/[token]
And these are the embed links to use for the iframe:
http://www.youtube.com/v/[token]
http://player.vimeo.com/video/[token]
https://www.dailymotion.com/embed/video/[token]
https://www.kickstarter.com/projects/[token]/[token]/widget/video.html
Here is the code I've got so far
if (videoURL = href.match(/(youtube|youtu|vimeo|dailymotion|kickstarter)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+)|video|projects)\/([\w-]+)\/([\w-]+)/)) {
var src = '';
if (videoURL[1] == 'youtube')
src = 'http://www.youtube.com/v/' + videoURL[4];
if (videoURL[1] == 'youtu')
src = 'http://www.youtube.com/v/' + videoURL[3];
if (videoURL[1] == 'vimeo')
src = 'http://player.vimeo.com/video/' + videoURL[3];
if (videoURL[1] == 'dailymotion')
src = 'https://www.dailymotion.com/embed/video/' + videoURL[6];
if (videoURL[1] == 'kickstarter')
src = 'https://www.kickstarter.com/projects/' + videoURL[6] + '/' + videoURL[7] + '/widget/video.html';
if (src) {
var iframe = $('<iframe>', {
src: src,
frameborder: 0,
vspace: 0,
hspace: 0,
scrolling: 'no',
allowfullscreen: ''
});
$container.append(iframe);
}
iframe.load(function() {
$loader.remove();
});
} else {
$this.liteboxError();
$loader.remove();
}
But currently, only KickStarter videos are working, the rest just return the liteboxError. However if I remove the KickStarter part of the regex, like this:
videoURL = href.match(/(youtube|youtu|vimeo|dailymotion)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+)|video|)\/([\w-]+)/)
Then it's only the DailyMotion videos working, and again if I remove the DailyMotion regex, like this:
videoURL = href.match(/(youtube|youtu|vimeo)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+))/)
Then the YouTube and Vimeo videos work fine.
Was just hoping someone could shine some light as to what's wrong with the regex I'm using?
Since the URLs have completely different types of nests for giving you the token to actual video, I think you'd need to nest them one inside the other:
(youtu\.be|((youtube|vimeo|dailymotion|kickstarter)\.com))/(watch\?v=([-\w]+)|video/([-\w]+)|projects/([-\w]+)|([-\w]+))
You can see and test some cases here
With the help of hjpotter92, I managed to get this code working for my regex:
if (videoURL = href.match(/(youtube|youtu|vimeo|dailymotion|kickstarter)\.(com|be)\/((watch\?v=([-\w]+))|(video\/([-\w]+))|(projects\/([-\w]+)\/([-\w]+))|([-\w]+))/)) { }
Then obviously changing the group numbers accordingly when using videoURL[*] to insert the data to the src variable!
I don't know why, but my Javascript only works once in Firefox and IE (but it works fine in Chrome). Does anybody know why?
<script type="text/javascript">
function changeDivImage()
{
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
if (imgPath == "url(images/1.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage ="url(images/2.jpg)";
}
else if (imgPath == "url(images/2.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/3.jpg)";
}
else if (imgPath == "url(images/3.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/1.jpg)";
}
}
</script>
Script is triggered by clicking on image
<img src="images/leftarrow.png"
value="Change Background Image"
onclick="changeDivImage()" />
Browsers tend to normalise CSS properties in different ways. IE and Firefox put quotes around the URL, for instance.
So, perhaps you should try this instead:
var div = document.getElementById('div1'),
imgPath = parseInt(div.style.backgroundImage.match(/\d(?=\.jpg)/) || ["0"],10),
newnum = imgPath%3+1;
div.style.backgroundImage = "url(images/"+newnum+".jpg)";