Jquery: TypeError: text is undefined - javascript

I've got a little code snippet to 'hack' away at some templated code I can't fix normally.
<script>
jQuery( document ).ready(function() {
jQuery(".avatar").each(function() {
var text = jQuery(this).attr("src");
text = text.replace("-64x64.jpg", ".jpg");
text = text.replace("-80x80.jpg", ".jpg");
text = text.replace("-32x32.jpg", ".jpg");
text = text.replace("-28x28.jpg", ".jpg");
text = text.replace("-16x16.jpg", ".jpg");
text = text.replace("-128x128.jpg", ".jpg");
jQuery(this).attr("src", text);
});
});
</script>
Upon this script above firing in the browser I'm getting the following error in the console:
TypeError: text is undefined
text = text.replace("-64x64.jpg", ".jpg");
Racking my brain but coming up with nothing. Tried using var text; to try and define it at the start of the script and also tried using a different variable name in case it was conflicting with something both of which did nothing....

This means that at least one of the elements with class avatar does not have a src attribute. attr returns undefined if the element in question doesn't have the attribute at all.
You can put a guard in (if (text)). Here's an example. Also note that there's zero reason to use jQuery(this).attr("src"); just use this.src:
jQuery( document ).ready(function() {
jQuery(".avatar").each(function() {
if (this.src) {
this.src = this.src.replace("-64x64.jpg", ".jpg")
.replace("-80x80.jpg", ".jpg")
.replace("-32x32.jpg", ".jpg")
.replace("-28x28.jpg", ".jpg")
.replace("-16x16.jpg", ".jpg")
.replace("-128x128.jpg", ".jpg");
}
});
});
You can also probably make that code a bit more robust using a regular expression:
jQuery( document ).ready(function() {
jQuery(".avatar").each(function() {
if (this.src) {
this.src = this.src.replace(/-(\d+x\d+)\.jpg$/, ".jpg");
}
});
});
That will replace -DIGITSxDIGITS.jpg with .jpg, without being specific about what the digits in each case are. \d means "any digit", and the + after it means "one or more".

Related

How to get JQuery to swap picture prior to page being displayed

I've got the following script which swaps the source of an image. However currently this happens after the page loads so the user experiences a split second of seeing one picture before it switches to the correct image.
<script>
window.onload = function () {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
};
</script>
How can I get the image to switch before loading?
Note I've also tried:
<script>
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
});
</script>
but this results in the same thing occurring
Both of the window.onload or jQuery's $(function()... functions are only called when the page is fully loaded.
The closest you could get is to add the function to the images onload handler.
<img src="..." onload="function() {...}">
But I suspect the same will still occur.
If the image's src needs to be set using javascript then you could try dynamically creating the image and adding it in where you need it, using something like the following.
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
var imgElement = $('<img>').attr("src", "/Content/Images/" + winnerName + ".jpg");
$("#pictureDiv").append(imgElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pictureDiv"></div>

Hiding Content Based on Content of URL String

I am trying to hide a certain fieldset with an id of "retail" based on if the URL has 'studio' as a part of it. The URL would read as follows:
/island-careers/studio/accounting/accountant/apply.html
Here is my script I have written up but I can't seem to get it to recognize if 'studio' is in the URL.
<script>
jQuery(document).ready(function(){
var path = window.location.pathname;
console.log(path);
var split = window.location.href.split('/');
console.log(split);
console.log(split[4]);
if (split[4] === 'studio') {
jQuery('#retail').css('display, none');
}
});
</script>
The "console.log(split[4]); was to find the location of 'studio' in the array. There must be something wrong with my IF statement I guess. I also tried this method but it didn't work for me either:
<script>
jQuery(document).ready(function(){
var path = window.location.pathname;
console.log(path);
if (path.indexOf('studio') >= 0) {
jQuery('#retail').css('display, none')
}
});
</script>
Your jQuery line to change the CSS should be:
jQuery('#retail').css('display', 'none');

Index with switch statement

I'm trying to figure out how to combine this code into a switch statement using an index. I'm using this code to allow someone to click on a thumbnail, play that video in the player along with change the title depending on which video is played. Thanks in advance.
<script>
// Play the video
$( "#video-1, #item1" ).click(function() {
flowplayer().play("video1.mp4");
});
$( "#video-2, #item2" ).click(function() {
flowplayer().play("video2.mp4");
});
$( "#video-3, #item3" ).click(function() {
flowplayer().play("video3.mp4");
});
$( "#video-4, #item4" ).click(function() {
flowplayer().play("video4.mp4");
});
$( "#video-5, #item5" ).click(function() {
flowplayer().play("video5.mp4");
});
// Change title
function changeTitle(name)
{
document.getElementById("show-title").innerHTML = "Now playing " + name;
}
// Add and remove active class
$('#playlist li').on('click', function(){
$(this).addClass('active').siblings().removeClass('active');
});
</script>
The cleanest way to do this is to add a common class name to all the items that you want to be video click enabled (all the #itemX and #video-X elements) so then you can use a very simple piece of javascript for the common click handler. You then extract the digits out of the click on element's ID value in order to figure out which video to play:
$(".videoPlay").click(function {
var num = this.id.match(/\d+/)[0];
flowplayer().play("video" + num + ".mp4");
});
If you cant add the common class, then you can just list out all the selectors you want included:
$("#video-1, #video-2, #video-3, #video-4, #video-5, #item1, #item2, #item3, #item4, #item5").click(function() {
var num = this.id.match(/\d+/)[0];
flowplayer().play("video" + num + ".mp4");
});
Or, if you have no other ids that might get caught up in a partial id match, you can use the starts with selector logic, though I prefer to avoid this because it's not fast for the browser to resolve (it has to look at every single object that has an ID). I'd perfer listing the actual ids or using a common class name:
$("[id^='video-'], [id^='item']").click(function() {
var num = this.id.match(/\d+/)[0];
flowplayer().play("video" + num + ".mp4");
});
If there is no correspondence between the id of the clicked-on item and the video filename, then you need to create some sort of map between the two. My favorite technique would be to specify a data-video custom attribute on the actual element:
<div class="videoPlay" data-video="thor.mp4">Click me to Play a Video</div>
And, then the JS would be:
$(".videoPlay").click(function {
var fname = $(this).data("video");
flowplayer().play(fname);
});
You can have as many of these HTML elements as you want and just make sure each one specifies the video file you want that element to play and the JS doesn't have to change at all as you add more and more.
This should work :
$( "[id^='video-'], [id^=item]" ).click(function() {
var vid = this.id.replace(/(\d)|./g, '$1');
flowplayer().play("video"+ vid +".mp4");
});

jQuery append img element with url on src not working in IE and FF

I have an image tag that retrieves the src by an url, like:
<img src="http://localhost:2000/User/GetImage/1" />
That element is generated by jQuery, that is:
this.updateImage = function()
{
console.log("Change me!");
var context = this;
var imageSrc = webApiUrl + "User/GetImage/" + this._id;
$("#ga-application-header .user-info-image").each(function()
{
$(this).empty();
/* First try */$(this).append($("<img title='" + context._firstName + " " + context._lastName + "' />").attr("src", imageSrc));
/* Second try*/$(this).append("<img title='" + context._firstName + " " + context._lastName + "' src='" + imageSrc + "' />");
});
}
That lines with coments - first and second try - are the way I've tried the get this achieved.
Now the most important detail. When page is loaded, this function is called and displays the image. This works. But if I call it again(when user change it's picture) the image doesn't shows in IE and FF. Only on Chrome. IE and FF don't even open an image request(on network tab in console) for it. Note that the console.log text "Change Me!" is always called.
The issue is caused by the browser caching the image. The fix is to append a random query string to the image source.
First, I tend to use the following pattern as opposed to string concatenation.
var img = $('<img/>').attr('title',context._firstName).attr('src',imageSrc);
$(this).append(img);
Second, inside your this.updateImage, could you console.log/dir(this), I'm guessing your context isn't proper, you may want to do a var that = this, to keep your references in check.
I just ran into the same issue with IE.
This helped me:
Instead of
$form.find( ".classname" ).append( content );
This worked in IE and all other browsers:
$form.find( ".classname" ).html( $form.find( ".classname" ).html() + content );
Hope it helps somebody here...

Jquery .html, Firefox encodes qoutes in attributes

I have a hotfix app which generates HTML slides. The modules are built in Jquery with the background as inline CSS (the best solution i could come up with since they are unique per instance).
The problem is that firefox converts the quotes in the style attribute into:
<div style="background-image: url("bigspace-template.jpg");"
class="nuiOpenspace t1 skin1">
The webkit browsers have no issues with this.
They only way i have been able to get the background attribute is by:
// Build function, shortened
openspace.build = function(){
// ...
var bgstr = 'background-image: url('+ this.val_image + ')';
$o = $('<div class="nuiOpenspace"></div>').attr('style', bgstr);
// ...
}
This is then output appended to the document:
function Sandbox(){
var $sandbox = $("#sandbox");
this.fill = function(o) {
$sandbox.empty();
$sandbox.append(o);
};
// ...
}
I then get the HTML from the dom, convert to string and then output it in a textarea:
function Source(){
this.print = function(o, c_val){
//var parsed_html = this.parse(o, c_val);
//var pretty_html = "";
//pretty_html = style_html( parsed_html );
//console.info(x.replaceAll('&qout;', 'x'));
$code.text( style_html($("#sandbox").html()) );
};
}
var source = new Source();
I´ve tried search and replace but firefox keeps changing to / adding ". Any ideas?
As far as I know, the " is a ", so you have " inside something that is in between its own ". That can never work like this I think.
If you would've changed the origional code (the one that didn't work in firefox) to valid code (using either escapes or a combination of ' and " instead of "nested" "), wouldn't you be closer to a solution?

Categories