I am currently editing a theme code in which the following javascript snippet occurs:
...
void 0 === Cookies.get("Key") && e("#modal").fadeIn(),
e("#modal .newsletter-close a").on("click", function (e) {
e.preventDefault();
}),
...
First of all, I don't understand the first line.
void boolean && function
Secondly, I don't understand that the functions in the snippet are separated with commas even though these functions are all inside another one and not in an object.
I hope someone can explain what is happening there (not specifically in this snippet, but generally for this spelling) or give me a keyword to google for
void forces the return of undefined. This is rarely desirable, however it also forces the line after it to execute, and then throws away the result of that execution. Most often you'll see it used to stop a link from going to it's href. Instead, it'll have something like href="javascript:void(performAction());". In which case, clicking the link will cause the performAction() function to fire and the whole thing returns undefined and the anchor doesn't go anywhere.
The double ampersand is a logical operator, and is saying if the cookie portion is true, and the modal portion is true, then the next thing.
The comma operator acts as a shorthand break between statements.
This is a shorthand way of saying, immediately execute this shorthand if, if the Key cookie is equal to 0 (likely means not set), and the modal is faded in, then attach the click event to the close button of the modal.
More than likely, this modal is dynamically created, and the click event isn't attached when the $(document).ready() function fires, because the modal doesn't exist yet. This is a way to allow the modal to have a click event in the shortest amount of code they could think of.
More here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
Related
I'm in the process of reviewing a fairly straightforward ES6 implementation of a clickable, double-sided flashcard on Codepen.
I'm able to parse 99% of the code, but this toggleTurn function has left me scratching my head.
Specifically, I'm wondering:
(1) What is the purpose of setting the turned value to to its logical opposite (!turned) at the beginning of this function?
(2) Why is it necessary to pass the event object to this function as a parameter? Wouldn't it be simpler & easier to just invoke a toggleTurn() function within an event listener?
function toggleTurn(e) {
turned = !turned;
if (turned) {
this.classList.add("turned");
} else {
this.classList.remove("turned");
}
}
I'm sure the answers here are blindly obvious, so many thanks in advance for the time & patience!
What is the purpose of setting the turned value to to its logical
opposite (!turned) at the beginning of this function?
If the "turned" class is added on the html element, then that means turned is true. Negating its value will give false which will execute the else block.
Similarly, if the "turned" class is not added on the html element, then that means turned is false. Negating its value will give true which will execute the if block.
You could simplify the function using the toggle method:
function toggleTurn() {
this.classList.toggle("turned");
}
Why is it necessary to pass the event object to this function as a
parameter? Wouldn't it be simpler & easier to just invoke a
toggleTurn() function within an event listener?
If it's not used in the function, then it's not needed. You can remove it if you want to. It does however serve as a reminder that the function is used as an event listener.
In this code it makes no sense to have the turned variable, because it's only being used to toggle the class name. In fact, the toggleTurn() function could just be a one-liner:
function toggleTurn(e) {
this.classList.toggle("turned");
}
And as for the e, as you can see it's not in use. Event listeners automatically get the event parameter and there are different philosophies of whether you should include unused parameters in your function definition or not. There's nothing wrong with keeping it in there.
I want to modify the output of the functions (just say RANDOM examples, apologies for any code mistakes):
ng-if=!pfile.isgame
ng-if=! pfile.examplefile
-from false to true before it even has the page has any chance to drop any code on the page. How can I make it so I can append code to the page to the very beginning of the page to force every output of these particular functions to go true, on a live page?
This is definitely possible, I'm not sure where the function would be however the elements you can actually see the arguments on the page and it doesn't not look server sided at all, its just how its done. I read many articles but it many of them have not really helped me.
I am aware of Event Listener Breakpoints, its just the problem if I'm choosing the right one.
Thank you and I really appreciate it just if you can please dum down the explanation for me as even though I do understand HTML and JavaScript to an OK standard, I am still a massive beginner. This is something I always wanted to try out.
Hopefully I have understood your question correctly. There are a couple of options and the answer will depend on whether the functions are declarations or expressions.
If they are declarations, they get hoisted to the top on first pass, so that by the time your code begins execution, the function already exists and you can overwrite it early on.
If it's a function expression, you have to wait until the function expression has been created.
Example 1 (Function Declaration):
I have a function declaration on my page, which returns true if there is a remainder in the calculation, otherwise false. I execute it on page load. The output is false here:
function hasRemainder(first, second) {
return (first % second != 0);
}
console.log(hasRemainder(10, 5));
false
I have now added the Script First Statement breakpoint in DevTools, so that the debugger breaks before any script is run:
I re-open the page and the execution pauses. I now run the following code in the Console tab to override the hasRemainder function so that it always returns true:
hasRemainder = function() {
return true;
}
Finally, I click Play to continue execution. You can long click to select Long Resume, which skips breakpoints for 500ms so that you don't get caught for very single breakpoint thereafter.
true
The output this time is true as you would expect.
Example 2 (Function Expression):
We can't rely on the early breakpoint this time because the function won't exist yet. We need to add the breakpoint just after the function expression has been created.
Search for the functions using Cmd+Opt+F (Mac) or Ctrl+Shift+F (Windows).
When you are in the file with the function expression, put a breakpoint at the end of the function. When the debugger pauses, run the overriding function into the Console, and then press play to continue execution.
I'm updating an existing website running on Expression Engine. So far, I've stayed away from any code I didn't write or couldn't understand. I recently must have altered some bit of code someplace (helpful, I know) and now a block of JS I didn't write is causing an error that seems to bypass the document.ready() event. The window.load() event however is still taking place.
In the Chrome DevTools Console, the error "Uncought TypeError: Cannot call method 'replace' of UNDEFINED" points to the definition of a function "fixedEncodeURIComponent" pasted below.
$("#MessageContainer.Counted").counter({
type: 'char',
goal: 250,
count: 'down'
}).change(function(){
var TEMP = fixedEncodeURIComponent($(this).val());
$("#Message").val(TEMP);
});
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
function fixedEncodeURIComponent (str) {
str=str.replace(/"/g, '');
return encodeURIComponent(str).replace(/[!'()*]/g, escape);
}
As I interpret the error, this function is being passed a variable that is not a string. I added an alert(str) to the function definition and the result was UNDEFINED as I expected. The first of several unknowns for me is which call to the function 'fixedEncodeURIComponent' is being passed a bad variable. I assume that it's the first call, but that's just a guess. It so happens that this first call contains a syntax I have never encountered before. I don't know how to interpret what happens when $(this) is passed as a function argument.
Any insights would be greatly appreciated. Also, if there's more information you need please let me know. The client's site is password protected but I can include any code you request.
Thank you.
I'm taking a guess that the }); on line 3 is exiting a document.ready context. If that's the case then your second call to fixedEncodeURIComponent may be getting called before the DOM is even loaded.
Start by wrapping
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
in a
$(function() {
// code
});
block. If that doesn't work, check that #MessageContainer.Test actually matches an element. Since this is code you inherited, the class name "Test" clues me in that the block in question might be a remnant of someone trying to debug an issue and maybe it should have been removed.
I suspect $("#MessageContainer.Test") since it looks like its supposed to be an ID selector instead of what it actually is when jQUery parses it(which is an ID selector combined with a class selector). $("MessageContainer\\.Test") allows you to select an element with ID MessageContainer.Test
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is the point of void in javascript
What does “javascript:void(0)” mean?
Everywhere I see this javascript:void(0); to do nothing I think. (instead of this javascript:; can be used I think)
And that day I see javascript:void(x=document.getElementById('mytext').value);void(document.getElementById('mylabel').innerHTML=x); code in the page.
My question is very simple, why void? What void does?
MDN documentation page
This operator allows inserting expressions that produce side effects
into places where an expression that evaluates to undefined is
desired.
The void operator is often used merely to obtain the undefined
primitive value, usually using "void(0)" (which is equivalent to "void
0"). In these cases, the global variable undefined can be used instead
(assuming it has not been assigned to a non-default value).
void is an operator which returns undefined, although evaluation the following expression. The brackets are not needed.
In javascript:-urls it is used because any return value would overwrite the current document (like document.write()).
I believe this is a sort of alternative to simply terminating the click even in jQuery for example. When you attach a click handler to an anchor tag, you should always return false at the end of the handler -
$("#btn").on('click',function(){
// make toast
return false;
});
Returning false cancels any other actions that would have been executed by the event.
When you attach a javasctipt:void(0) to the onclick of an element, you are preventing that event from doing anything and leaving all the work to your JavaScript.
I seem to be observing at least one case where a callback function passed to a jQuery effect function will execute repeatedly if there's an error while it's executing.
For example, see this JS Fiddle, featuring the following code:
$('#awesome').fadeOut(400,function () {
log('fading out...');
dieInAFire();
});
log appends whatever's passed to it to a div... but dieInAFire doesn't exist. Rather simply stopping execution, however, the anonymous function appears to be getting called over and over, as evidenced by the growing number of appearances of 'fading out...' in the log div.
Is this the expected behavior? If so, why?
It's a known bug. See the report here.
I just submitted a comment on the bug that patrick dw posted.
Changing the line:
options.complete.call(elem);
To:
setTimeout(function(){
options.complete.call(elem);
}, 0);
Causes the callback to execute asynchronously, and if it will no longer stop execution if it throws any errors. IMO it's better than using a try catch since it doesn't suppress the exception.
If you want to edit your minified version, and you use the latest jQuery, you can search for e.complete.call(d) and replace it with setTimeout(function(){e.complete.call(d)},0)