Rectangle 27 5

The || operator returns its left hand side if resolves to be a true value, otherwise it returns its right hand side.

So it means the same as:

var variable;
if (obj1){
    variable = obj1;
} else {
    variable = obj2:
}

It is a common pattern and not usually considered bad practise.

if (obj)
if (typeof obj !== "undefined")

javascript - What does this bit of code mean? - Stack Overflow

javascript
Rectangle 27 5

It means the code will work in XML / XHTML and HTML without having to mess with CDATA

Nice find on the previously answered question. Though it can still be made to work with both XHTML and HTML "without having to mess with CDATA" and without needing unescape: stackoverflow.com/questions/728697/

javascript - Why does Google unescape their Analytics tracking code? -...

javascript google-analytics
Rectangle 27 5

It means the code will work in XML / XHTML and HTML without having to mess with CDATA

Nice find on the previously answered question. Though it can still be made to work with both XHTML and HTML "without having to mess with CDATA" and without needing unescape: stackoverflow.com/questions/728697/

javascript - Why does Google unescape their Analytics tracking code? -...

javascript google-analytics
Rectangle 27 3

Note to the author of the question

This is just a guess because all your main scripts and JSON data are missing, so I can't test it. However, these changes will hopefully make it work for you. Please test them!

<div id="tabs" class="content-wrapper">

you should add this code exactly as written to your page (I noticed that you had not included this in your page yet):

Then, inside of your function configLoaded you need to add a second block of code (the new changes to your code are marked by NEW):

function configLoaded() {
    $('#lblLoading').hide();
    var imgLoad = imagesLoaded('body');                    /* NEW */
    imgLoad.on( 'progress', function( instance, image ) {  /* NEW */
        var result = image.isLoaded ? 'loaded' : 'broken'; /* NEW */
        image.img.src = 'Your-Placeholder-Image.png';      /* NEW */
    });                                                    /* NEW */
    //$('bookDropDown').Attr('disabled', false);
    //$('moviesDropDown').Attr('disabled', false);
    //$('musicDropDown').Attr('disabled', false);
}

This way when your menus load new images, the progress/error handler will be attached again (in case that is needed after the new images are generated). The most important thing of course, is that you include the imagesloaded.pkgd.min.js script code, because the second part of code can do nothing without that.

All of my suggestions work 100% of the time for me, fully tested like proper Stack Overflow answers should be. Unfortunately, these solutions have not had the chance to be properly incorporated into your code because I am lacking your full code or a self-contained example.

The nutshell that you have given, and the JS Fiddle you provided in another question (with only one line of JavaScript there), and the JS Fiddles from you and other people in various comments are all giving me a clear picture of what your problem is. Yet without enough of your actual code (ideally all of it), I cannot show you how to incorporate the solution properly--it would be like a car mechanic trying to fix a car when the car isn't there, or a math teacher trying to teach someone math problems using hand motions instead of something to write with.

I can make any of my solutions work for you, but all I need is a link to your full code which contains the problem, or if for some reason it is confidential, then at minimum a self-contained example. Please see: http://sscce.org

Would you mind providing a link to your full code or a self-contained example? I would be happy to modify it so that it works for you. I.e., if these solutions aren't working for you, then there is something else in your code that needs to be fixed, and until that point, I am providing this answer for the benefit of the community.

<script src="//desandro.github.io/imagesloaded/imagesloaded.pkgd.min.js">
</script>

That script provides the ability to properly detect all broken images on the page. Read about it here, including a demo which shows exactly the functionality that you are wanting to achieve for your own site: http://desandro.github.io/imagesloaded/

Then add one of the following code options to your existing JavaScript. (You may also need to remove all other attempts at detecting image loading errors from your code to make sure there is no conflict.)

This code should work just as well or better, and is even shorter.

"In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event."

Interpretation: You cannot reliably catch image loading errors with a jQuery selector in a document where HTML content is being generated asynchronously from the jQuery command.

Therefore, when registering an error handler for an image (such as replacing it with a "no image available" image), it is important to register the error handler on the image before the image element has been inserted into the DOM or becomes a live document fragment. If your image src exists in a pure JavaScript string, you need to make sure than an onerror handler is specified before that string is converted to a live document fragment. If your image src exists in a JavaScript image object, then it is already too late to specify an error handler--in that case, you must specify the handler before the src.

Otherwise, there is a race condition going on after the image element has been inserted into the DOM, and before registering the event handler. An image can return a 404 Not Found very quickly since no image data need to load. If the event handler is not fully attached before the 404 has been detected, then the event handler will not be called.

The way your code is constructed, it forms an HTML string then converts it to a live HTML object by using it as the argument to the jQuery constructor, and only then sets the error handler for the img elements that it contains. This causes the same problem as having HTML source that contains no onerror attribute, and then afterwards trying to set the error handler with a script. The behavior you mention

This works for me, just changing the last few lines in your JS Fiddle, and setting the attribute in the HTML string before anything is converted to actual live elements:

imageError = function(it) {
    $(it).attr("src","placeholder.jpg");
};

htmlBuilder = htmlBuilder.replace(/<img/g, '<img onerror="imageError(this)"');
var jObject = $(htmlBuilder);

 $("#container").html(jObject);

You indicated that this does not work, but it should (after changing placeholder.jpg and #container to your own values), and a proper diagnosis requires me to see everything in your page, since anything else you are doing could affect why this isn't working for you.

Properly implementing the solution of using an error handler requires you to register the onerror / error event handler before specifying the src of the image in a live document fragment.

There are other alternatives, however. For example, after the entire document is loaded, you can make a function which loops through all of the page's image elements, locating those that failed to load, and changing their src attribute.

I can't guarantee that it will work because as I mentioned, anything else you are doing could affect why something isn't working for you.

This method of solving the problem also has a plug-in that may work with your code. https://github.com/desandro/imagesloaded

var imgLoad = imagesLoaded('body');
imgLoad.on( 'always', function() {
  console.log( imgLoad.images.length + ' images loaded' );
  // detect which image is broken
  for ( var i = 0, len = imgLoad.images.length; i < len; i++ ) {
    var image = imgLoad.images[i];
    var result = image.isLoaded ? 'loaded' : 'broken';
    console.log( 'image is ' + result + ' for ' + image.img.src );
    if (result == 'broken')
        image.img.src = 'Content/NoImageAvailable.png'; /* DOUBLE CHECK THE SRC */
  }
});

Again, it is possible that something else you are doing will conflict with this plug-in, but it is definitely worth a try! It works perfectly in my example here:

Since image error events don't bubble, a global error tracking function solution is not possible, leaving two general ways of dealing with this problem:

  • A local way of individually registering an error handler for each image, preferably before its src is specified, but at minimum before it becomes a live HTML fragment or JavaScript image object. The advantage of this method is that error handling will happen immediately for each image, replacing the broken image icon with your placeholder image as soon as the 404 Not Found is detected.
  • A global way of locating broken images throughout the page. This method has the disadvantages of not immediately fixing broken images (lots of time may be spent loading other large images before finally the broken images will be fixed) and of not working for images which may be added to the page later after the initial loading event happens (e.g., images loaded later from Ajax data), but it has the advantage of working for images which are loaded into the page by various mechanisms, like your hmtlBuilder string, that would require complete re-programming to allow images to individually have error handlers assigned.

The ideal way to solve this problem (which doesn't exist) would be for browsers to "bubble" the image error event into a general document error event, which could be monitored by a single event handler, checking to see if the source of the error event was an img element, and if so, then checking the kind of error and replacing an image not found with the desired placeholder.

Once again, I would be happy to help you make one of these two correct solution methods work if you send me a link to your entire page. The specifics of making any JavaScript work with your code requires one to see all of your code since there can be other lurking variables.

Nope, that doesn't work, either. The only thing different in my code is the name of the replacement image: htmlBuilder = htmlBuilder.replace(/<img/g, '<img onerror="imageError(this)"'); ...and the id of the div that gets the html: $("#BooksContent").html(jObject);

@ClayShannon Can you provide a link to the file on your site where I can simply refresh it a few times until I see some images that fail to load but don't show the error image properly? Then I could debug from there. I don't know if I can see what you are seeing on JS Fiddle, but I could probably see it if you had a normal page that I could just refresh until I see the problem happening.

@ClayShannon I see your fiddle here jsfiddle.net/clayshannon/cMYEH/1 but I don't see the JavaScript part of it. Is that the right link I should be looking at? I'll check back tomorrow if you don't have a chance to get back to me with a link before I get some sleep for the night.

javascript - Why does my img error function fail? - Stack Overflow

javascript jquery html razor asp.net-webpages
Rectangle 27 3

The first seems an email validation for addresses in a specific form:

(name).(name).(name) ... @ (name).(name).(name) ... .(domain)

where name is a sequence of a..z, numbers or the charater - and domain is a sequence of 2 to 4 letters. In the specific:

  • [_a-z0-9-]+ = one or more of underscore, lowercase, number or dash
  • * = the part dot+name can be present zero or more times
  • @ = the @ sign
[a-z0-9-]+
(\.[a-z0-9-]+)*
dot+name
  • \. = a dot
[a-z]{2,4}

The second one seems instead a bad password validation requiring a sequence of letters and digits with at least a letter and at least a digit.

The (?= ... ) form is called "zero-width look-ahead assertion" and it means that the contained expression must validate but it doesn't "use" characters:

  • (?=.*[0-9]) = any sequence of chars and a digit (just looking ahead)
  • (?=.*[a-zA-Z]) = any sequence of chars and an alphabetic character (just looking)
([a-zA-Z0-9]+)

The first two look-ahead assertions are used to check that at least one number and at least one letter are present in the expression that must be composed of just letters and numbers.

javascript - What does this regex code means - Stack Overflow

javascript regex
Rectangle 27 48

You're immediately calling an anonymus function with a specific parameter.

(function(name){
  alert(name);
})('peter')

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict()
(function($){
  var obj = $('<div/>', { id: 'someId' });
})(jQuery)

Can this function be given a name? or does it have to be anonymous?

coding style - What does this "(function(){});", a function inside bra...

javascript coding-style scope anonymous-function javascript-namespaces
Rectangle 27 48

You're immediately calling an anonymus function with a specific parameter.

(function(name){
  alert(name);
})('peter')

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict()
(function($){
  var obj = $('<div/>', { id: 'someId' });
})(jQuery)

Can this function be given a name? or does it have to be anonymous?

coding style - What does this "(function(){});", a function inside bra...

javascript coding-style scope anonymous-function javascript-namespaces
Rectangle 27 2

Putting the () around the function() { ... } makes it an expression vs. a statement. Because it's an expression which produces a function value the () at the end invoke the produced function.

function () { 
  var b = 3;
  a += b;
}();

This produces a syntax error as the () are essentially trying to invoke a statement.

(function () {
  var b = 3;
  a += b;
});
function

javascript - What does this syntax mean? (function () {//code})() - St...

javascript
Rectangle 27 2

(\.[_a-z0-9-]+)* matches the group \.[_a-z0-9-]+ 0 or more times. I assume it's easy to understand what this matches: a dot, followed by alphanumeric characters, dash - or underscore in any order and at least one.

( ... ) is being used to group those characters. * means repeat 0 or more times.

(\.[a-z0-9-]+)* is similar to the above, with the exception that underscores are not allowed here.

(\.[a-z]{2,4})$ will match a dot, followed by 2 to 4 alphabets and ensure that there are no more characters after that.

(?= ... ) in regex is called a positive lookahead. It means that the regex will match only when the regex inside is satisfied.

^ checks the start of the string.

(?=.*[0-9]) will make sure the string has at least 1 digit. .*[0-9] will match only when a digit is matched.

(?=.*[a-zA-Z]) will make sure the string has at least 1 letter. .*[a-zA-Z] will match only when a letter is matched.

The advantage of using a lookahead here instead of directly using the character class [a-zA-Z0-9]+ is that it can be used to check the whole string without 'moving'.

The position of the check remains at the start of the string when the string is checked for the digit, and still remains at the start when it is checked for letters.

This in turn allows the regex to ensure that both digit, and letters are present, something that [a-zA-Z0-9]+ alone cannot do since it matches Aaa (no digits) and 123 (no letters) just fine. Using the lookaheads ensure that there are both digits and letters in the match.

Note that not all email addresses will get correctly validated with this regex. There are numerous valid email address format that exist that the regex will tell as invalid. See this question.

javascript - What does this regex code means - Stack Overflow

javascript regex
Rectangle 27 2

You are correct, in ES6 this does throw an exception. There's two reasons why it doesn't for you:

  • node.js already implemented let - but it works correctly only in strict mode. You should use it.
  • babel does not appear to transpile the TDZ by default, as it is quite complicated and leads to lengthy code. You can however enable it with the es6.blockScopingTDZ/es6.spec.blockScoping option (but I'm not sure whether this worked in Babel 5 only and what happened in Babel 6 to them).

@Runjuu: the temporal dead zone - the thing that causes the access to throw despite being a declared variable.

Babel 6's TDZ is still pretty buggy, so not that many people use it I think.

@loganfsmyth: I don't know much about babel and its versions. Are you saying that it did work in Babel 5, but does not in 6? Do you have some links (maybe a tracking bug report) to back "still pretty buggy"? I have tried searching at phabricator.babeljs.io but can't seem to filter by version or sort by date. Also feel free to edit my answer directly if you have something relevant, or post your own :-)

As for TDZ in Babel 6, this case doesn't seem to be handled. I guess that es6.spec.blockScoping was replaced with babeljs.io/docs/plugins/transform-es2015-block-scoping plugin but it addresses block scopes only.

javascript - Why does this code not result in a ReferenceError? - Stac...

javascript ecmascript-6 babel-node
Rectangle 27 9

Because the ECMA standard section 12.9 states you can't have a new line between the return keyword and its expression.

revealing module pattern - Why does the { position affects this Javasc...

javascript revealing-module-pattern
Rectangle 27 8

One of JavaScripts worst features is Automatic Semicolon Insertion.

return; // a semicolon is implicitly inserted here

And this part is almost valid JavaScript, but not quite, so you get a syntax error:

{
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
};
return
    [ 1, 2, 3,
      4, 5, 6,
      7, 8, 9 ];

it would have just returned undefined all the time, and that would have been bad. ASI sucks, but were stuck with it now, especially since semicolonless code has become a fad.

return a
     + b
     + c;
return e
     / f /g;

Okay, okay, maybe that ones a bit contrived, and maybe this isnt entirely topical. But ASI is bad. I hope everyone gets that.

Thanks, that is an indepeth explanation

revealing module pattern - Why does the { position affects this Javasc...

javascript revealing-module-pattern
Rectangle 27 2

page.get()
page.get('title', function(title) {
  console.log('Page title is ' + title);
  return ph.exit();
});

javascript - Why does this code cause Node.js using the phantom module...

javascript node.js phantomjs
Rectangle 27 5

The pattern is called Revealing Module Pattern, a variation of the Module Pattern where the return value is used to expose properties of the module to make them public.

The advantage in returning some values at the end is that you can define all variables and functions in the same way using var, instead of making them properties of the module. The returned object contains some of the previous defined variables to make them public (unlike in your example where the functions are defined in the return statement)

In the standard Module Pattern you would define private and public function like this:

And for the Revealing Module Pattern the equivalent would be

var PageCode = (function () {

    var f1 = function() { /* ... */ }
    var f2 = function() { /* ... */ }

    return {
        f2: f2
    };
}());

This pattern along with the links at the top help a lot to clarify about what's going on. Also the link for the almost "duplicate" answer helps a lot as well. Thanks for the help!

@richie In JavaScript functions implicit returns undefined. Explicit can returns everything, for example object. Returned value after IIFE calls will be assigned to variable that IIFE is assigned. After that you can call some methods on PageCode

Javascript Code Structure - How Does This Work? - Stack Overflow

javascript
Rectangle 27 7

(function() {
    ...
})();

creates a function and calls it immediately, with its own scope. A common term for this is an IIFE - "immediately invoked function expression".

In this case, you've inadvertently combined the last two lines, so the single line comment mentioning bwalton has broken the code by removing the trailing ) ();.

Without the trailing () you have a function reference, but it's not invoked.

All you need to do to fix your copy of the code is add a carriage return after bwalton 5/11/11..

You're one parenthesis short, aren't you? It's worth noting that the initial opening parenthesis and it's closing pair can be left out, but serve as a convention (as a visual indicator) that this function will be immediately invoked. They are not required. However, the (); at the end is definitely required for invocation.

Thanks a lot, guys. Your combined comments helped me understand it completely. Cheers.:)

To clarify my last comment -- in the context of the above answer, the external parens are actually required, or the javascript parser will throw an error. The parser makes distinctions between function declarations and function expressions. The external parens are not required for expressions, for instance var i = function(){ return 10; }(); but are required for declarations, as above. See Ben Alman's article on IIFE's (Immediately Invoked Function Expressions)

@JordanArsenault FWIW, there's other ways of fooling the parser into recognising a function expression without enclosing it in parens.

javascript - What does (function() mean in this particular code segmen...

javascript ajax mozilla
Rectangle 27 7

(function() {
    ...
})();

creates a function and calls it immediately, with its own scope. A common term for this is an IIFE - "immediately invoked function expression".

In this case, you've inadvertently combined the last two lines, so the single line comment mentioning bwalton has broken the code by removing the trailing ) ();.

Without the trailing () you have a function reference, but it's not invoked.

All you need to do to fix your copy of the code is add a carriage return after bwalton 5/11/11..

You're one parenthesis short, aren't you? It's worth noting that the initial opening parenthesis and it's closing pair can be left out, but serve as a convention (as a visual indicator) that this function will be immediately invoked. They are not required. However, the (); at the end is definitely required for invocation.

Thanks a lot, guys. Your combined comments helped me understand it completely. Cheers.:)

To clarify my last comment -- in the context of the above answer, the external parens are actually required, or the javascript parser will throw an error. The parser makes distinctions between function declarations and function expressions. The external parens are not required for expressions, for instance var i = function(){ return 10; }(); but are required for declarations, as above. See Ben Alman's article on IIFE's (Immediately Invoked Function Expressions)

@JordanArsenault FWIW, there's other ways of fooling the parser into recognising a function expression without enclosing it in parens.

javascript - What does (function() mean in this particular code segmen...

javascript ajax mozilla
Rectangle 27 8

coding style - What does this "(function(){});", a function inside bra...

javascript coding-style scope anonymous-function javascript-namespaces
Rectangle 27 8

coding style - What does this "(function(){});", a function inside bra...

javascript coding-style scope anonymous-function javascript-namespaces
Rectangle 27 1

Ooh, that's cool. I don't understand why anyone would require all of those specific things for a password -_-

javascript - What does this regex code means - Stack Overflow

javascript regex