Reputation: 91
I have some code that works just fine, but I feel like it could be written better.
$mainTabs.click(function() {
$('video')[0].pause();
$('video')[0].currentTime = 0;
});
Can I re-write this so it is on one line instead of two? I tried the code below, but got the following error "Uncaught TypeError: Cannot set property 'currentTime' of undefined". The video still pauses, but doesn't rewind like it should. Am I doing something wrong, or is my first attempt as efficient as it gets? I suppose I could save $('video') in a variable, but was hoping to only have to use that selector once anyway.
$mainTabs.click(function() {
$('video')[0].pause().currentTime = 0;
});
Upvotes: 0
Views: 50
Reputation: 61875
Only methods that are designed to be chained can be used in a chained fashion: it is the method itself returning "this" or a suitable chained object.
In this case pause()
is not designed to be chainable and does not return anything (the effect is that the method invocation expression results in the undefined value).
To write it "more efficiently" - mainly as in, less repeat - consider using a local variable.
$mainTabs.click(function() {
var video = $('video')[0];
video.pause();
video.currentTime = 0;
});
While there are times when a local variable may make a 'performance' difference due to avoiding re-evaluation of expressions, in this case there will be no practical performance difference as the evaluation is relatively fast and done very infrequently. Using a local variable does much more for clarity of intent in cases like this.
Upvotes: 4
Reputation: 4971
As currentTime()
requires a video object to operate on and pause()
just changes the state of the video object without returning the object itself you will get the error you describe.
It's not always more efficient to make just one line out of code that can be two or more. Consider how readable it is to other developers.
Upvotes: 1