Getting global var to use in a function - javascript

I'm working with this code to play and pause several audios:
jQuery(document).ready(function(){
var getaudio;
var audiostatus = 'off';
var current_id;
jQuery(document).on('click touchend', '.speaker', function() {
elemento = jQuery(this);
current_id = elemento.children("audio").attr("id");
clase = current_id.replace(/player/, '');
if (!jQuery('.c'+clase).hasClass("speakerplay")) {
getaudio = jQuery('#'+current_id)[0];
if (audiostatus == 'off') {
jQuery('.c'+clase).addClass('speakerplay');
getaudio.load();
getaudio.play();
audiostatus = 'on';
return false;
} else if (audiostatus == 'on') {
jQuery('.c'+clase).addClass('speakerplay');
getaudio.play()
}
} else if (jQuery('.speaker').hasClass("speakerplay")) {
getaudio.pause();
jQuery('.c'+clase).removeClass('speakerplay');
audiostatus = 'on';
}
});
// Here is my problem: I need to get the value of current_id...
jQuery('#'+current_id).on('ended', function() {
jQuery('.speaker').removeClass('speakerplay');
audiostatus = 'off';
});
});
In the last function I want to remove the class 'speakerplay' once the audio reached the end, but I can't get the value of current_id
Could anybody help me with this?
Thanks in advance!

don't use
var current_id;
use window.current_id directly
window.current_id = elemento.children("audio").attr("id");
jQuery('#'+window.current_id).on('ended', function() {

Related

How to write javascript by using STRICT & Proper Event Binding?

Need Some help here please.
Question:-
1)PROPER EVENT BINDING: Consider using the preferred .on() method rather than .click(), .bind(), .hover(), etc. For best performance and concise code use event delegation whenever possible
2)STRICT EQUALITY COMPARISON: For better performance please use Strict Equality Comparison.
I have no idea what to do actually and would appreciate some help.
This is my code (it’s quite long sorry):
Search Js:
$(document).ready(function(){
var submitIcon = $('.searchbox-icon');
var inputBox = $('.searchbox-input');
var searchBox = $('.searchbox');
var isOpen = false;
submitIcon.click(function(){
if(isOpen == false){
searchBox.addClass('searchbox-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('searchbox-open');
inputBox.focusout();
isOpen = false;
}
});
submitIcon.mouseup(function(){
return false;
});
searchBox.mouseup(function(){
return false;
});
$(document).mouseup(function(){
if(isOpen == true){
$('.searchbox-icon').css('display','block');
submitIcon.click();
}
});
});
function buttonUp(){
var inputVal = $('.searchbox-input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.searchbox-icon').css('display','none');
} else {
$('.searchbox-input').val('');
$('.searchbox-icon').css('display','block');
}
}
Menu:-
$(function() {
$('#main-menu').smartmenus({
subMenusSubOffsetX: 1,
subMenusSubOffsetY: -8
});
});
// SmartMenus mobile menu toggle button
$(function() {
var $mainMenuState = $('#main-menu-state');
if ($mainMenuState.length) {
// animate mobile menu
$mainMenuState.change(function(e) {
var $menu = $('#main-menu');
if (this.checked) {
$menu.hide().slideDown(250, function() { $menu.css('display', ''); });
} else {
$menu.show().slideUp(250, function() { $menu.css('display', ''); });
}
});
// hide mobile menu beforeunload
$(window).bind('beforeunload unload', function() {
if ($mainMenuState[0].checked) {
$mainMenuState[0].click();
}
});
}
});
Preloader:-
$(window).on('load', function() { // makes sure the whole site is loaded
$('#status').fadeOut(); // will first fade out the loading animation
$('#preloader').delay(350).fadeOut('slow'); // will fade out the white DIV that covers the website.
$('body').delay(350).css({'overflow':'visible'});
})
Counter:-
(function($){
$(window).on("load",function(){
$(document).scrollzipInit();
$(document).rollerInit();
});
$(window).on("load scroll resize", function(){
$('.numscroller').scrollzip({
showFunction : function() {
numberRoller($(this).attr('data-slno'));
},
wholeVisible : false,
});
});
$.fn.scrollzipInit=function(){
$('body').prepend("<div style='position:fixed;top:0px;left:0px;width:0;height:0;' id='scrollzipPoint'></div>" );
};
$.fn.rollerInit=function(){
var i=0;
$('.numscroller').each(function() {
i++;
$(this).attr('data-slno',i);
$(this).addClass("roller-title-number-"+i);
});
};
$.fn.scrollzip = function(options){
var settings = $.extend({
showFunction : null,
hideFunction : null,
showShift : 0,
wholeVisible : false,
hideShift : 0,
}, options);
return this.each(function(i,obj){
$(this).addClass('scrollzip');
if ( $.isFunction( settings.showFunction ) ){
if(
!$(this).hasClass('isShown')&&
($(window).outerHeight()+$('#scrollzipPoint').offset().top-settings.showShift)>($(this).offset().top+((settings.wholeVisible)?$(this).outerHeight():0))&&
($('#scrollzipPoint').offset().top+((settings.wholeVisible)?$(this).outerHeight():0))<($(this).outerHeight()+$(this).offset().top-settings.showShift)
){
$(this).addClass('isShown');
settings.showFunction.call( this );
}
}
if ( $.isFunction( settings.hideFunction ) ){
if(
$(this).hasClass('isShown')&&
(($(window).outerHeight()+$('#scrollzipPoint').offset().top-settings.hideShift)<($(this).offset().top+((settings.wholeVisible)?$(this).outerHeight():0))||
($('#scrollzipPoint').offset().top+((settings.wholeVisible)?$(this).outerHeight():0))>($(this).outerHeight()+$(this).offset().top-settings.hideShift))
){
$(this).removeClass('isShown');
settings.hideFunction.call( this );
}
}
return this;
});
};
function numberRoller(slno){
var min=$('.roller-title-number-'+slno).attr('data-min');
var max=$('.roller-title-number-'+slno).attr('data-max');
var timediff=$('.roller-title-number-'+slno).attr('data-delay');
var increment=$('.roller-title-number-'+slno).attr('data-increment');
var numdiff=max-min;
var timeout=(timediff*1000)/numdiff;
numberRoll(slno,min,max,increment,timeout);
}
function numberRoll(slno,min,max,increment,timeout){//alert(slno+"="+min+"="+max+"="+increment+"="+timeout);
if(min<=max){
$('.roller-title-number-'+slno).html(min);
min=parseInt(min)+parseInt(increment);
setTimeout(function(){numberRoll(eval(slno),eval(min),eval(max),eval(increment),eval(timeout))},timeout);
}else{
$('.roller-title-number-'+slno).html(max);
}
}
})(jQuery);
lucky,
Thanks for the helping hand, really appreciated.
So you meant to say that i should rewrite the code as bellow?
Updated JS:
// JavaScript Document
$(document).ready(function(){
"use strict";
var submitIcon = $('.searchbox-icon');
var inputBox = $('.searchbox-input');
var searchBox = $('.searchbox');
var isOpen = false;
submitIcon.on("click", function(){
if(isOpen === false){
searchBox.addClass('searchbox-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('searchbox-open');
inputBox.focusout();
isOpen = false;
}
});
submitIcon.on('mouseup', function(){
return false;
});
searchBox.on('mouseup', function(){
return false;
});
$(document).on('mouseup', function(){
if(isOpen === true){
$('.searchbox-icon').css('display','block');
submitIcon.click();
}
});
});
function buttonUp(){
var inputVal = $('.searchbox-input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.searchbox-icon').css('display','none');
} else {
$('.searchbox-input').val('');
$('.searchbox-icon').css('display','block');
}
}
1) Just replace all your submitIcon.click(function(){ with submitIcon.on("click", function(){ (and all other events).
2) Strict comparison is ===, in your code I can see for example if(isOpen == false){ - you should replace it with if(isOpen === false){; you can see well-defined difference between strict and non-strict equality comparison in this answer Which equals operator (== vs ===) should be used in JavaScript comparisons?

jQuery Pause Between Animation And Color Change

I want the div to fadeOut(), then when it's not visible to change the color and text, and then but only then, reappear.
Here's the code
var changeColor = function() {
var div = document.getElementById("div");
var p = document.getElementById("p");
var pText = p.innerHTML;
if (pText == "Click Me!") {
$(document).ready(function() {
$("#div").fadeToggle("fast");
}, function() {
$("#div").css("background-color", "aquamarine");
p.innerHTML = "More!";
}, function() {
$("#div").fadeToggle("fast");
});
} else if (pText == "More!") {
$(document).ready(function() {
$("#div").fadeToggle("fast");
}, function() {
$("#div").css("background-color", "coral");
p.innerHTML = "Click Me!";
}, function() {
$("#div").fadeToggle("fast");
});
} else {
return;
}
}
This is the link to codepen.io, the project My Project
DEMO - Change the javascript to the following:
var changeColor = function() {
var div = document.getElementById("div");
var p = document.getElementById("p");
var pText = p.innerHTML;
if (pText == "Click Me!") {
$("#div").fadeToggle("fast", function(){
$("#div").css("background-color", "aquamarine");
$("#div").fadeToggle("slow");
p.innerHTML = "More!";
});
} else if (pText == "More!") {
$("#div").fadeOut("fast", function(){
$("#div").css("background-color", "color");
$("#div").fadeIn("fast");
});
} else {
return;
}
}
Explanation:
Functions like fadeToggle can take a callback function which triggers after the animation is complete:
$("#div").fadeOut("fast", function(){
/*code here will trigger after animation is complete*/
});

Functions are not working in js prototype

I have developed a jQuery plugin with prototypal inheritance.But functions are only working for main init() function and other prototypes are not working.
My main function is
function Mynav(){
....
}
Mynav.prototype.linkBehaviour = function(){
$('.nav-menu li a').on('click', function(e) {
if ($(this).attr('href') !== '#') {
var link = $(this).attr('href');
$('#preloader').removeClass('fadeOut').addClass('fadeIn').fadeIn('slow');
setTimeout(function() {
window.location = link;
}, 1500)
} else if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
}
Mynav.prototype.verticalConverter = function(){
if (verticalNavOn) {
if(!verticalLive){
menuConverter();
verticalLive = true;
}
}
$(window).on('load resize', function(){
width = $(window).width();
if(width < 959){
if(!verticalLive){
menuConverter(); //This is a function also available with Mynav.prototype.menuConverter
header.removeAttr('style');
verticalLive = true;
}
} else{
convertHorizontal(); // Its also a function available
$('.header-fixed').attr('style',headerAttr);
verticalLive = false;
}
});
}
function init(){
new Mynav();
}
init();
In the upper codes linkBehaviour and verticalconverter is not working if i place linkBehaviour function in the main Mynav() it works then but not working in individual.
And i don't actually know about load/resize works with prototype or not .
Can any one help About the above two functions?
function Mynav(){
this.verticalNavOn = false;
}
Mynav.prototype.linkBehaviour = function(){
$('.nav-menu li a').on('click', function(e) {
if ($(this).attr('href') !== '#') {
var link = $(this).attr('href');
$('#preloader').removeClass('fadeOut').addClass('fadeIn').fadeIn('slow');
setTimeout(function() {
window.location = link;
}, 1500)
} else if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
}
/* --------------------------------------------------------------------------------------------------------
* I believe that is in trouble when the RESIZE happens.
*
* To make the BIND (on), you must pass the own plugin AHEAD. To be used in the event when it happens.
* --------------------------------------------------------------------------------------------------------
*/
Mynav.prototype.verticalConverter = function(){
var self = this;
if (self.verticalNavOn) {
if(!self.verticalLive){
self.menuConverter();
self.verticalLive = true;
}
}
// parse THIS plugin for EVENT
$(window).on('load resize', {self: self}, function(e){
// get SELF PLUGIN
var self = e.data['self'];
width = $(window).width();
if(width < 959){
if(!self.verticalLive){
self.menuConverter(); //This is a function also available with Mynav.prototype.menuConverter
header.removeAttr('style');
self.verticalLive = true;
}
} else{
self.convertHorizontal(); // Its also a function available
$('.header-fixed').attr('style',headerAttr);
self.verticalLive = false;
}
});
}
function init(){
var x = new Mynav();
// focing start function for tests
x.verticalConverter();
}
init();
See full changes HTML and JS in: http://jsbin.com/ricaluredi/3

how to control speed in this javascript toggle

i want control speed in this function , please help me!
<script>
function toggle(target)
{
var artz = document.getElementsByClassName('showhidemenu');
var targ = document.getElementById(target);
var isVis = targ.style.display=='block';
// hide all
for(var i=0;i<artz.length;i++)
{
artz[i].style.display = 'none';
}
// toggle current
targ.style.display = isVis?'none':'block';
return false;
}
</script>
If you just want a delay, try this:
function toggle(target, milliseconds)
{
setTimeout(function() {
var artz = document.getElementsByClassName('showhidemenu');
var targ = document.getElementById(target);
var isVis = targ.style.display=='block';
// hide all
for(var i=0;i<artz.length;i++)
{
artz[i].style.display = 'none';
}
// toggle current
targ.style.display = isVis?'none':'block';
return false;
}, milliseconds);
}
You'll lose the return value, though.
Call your toggle function with an timeout as per your requirement
Use
window.setTimeout(toggle(),2000);
This will call your toggle function after a delay of 2000 ms.
cant show this function with animation ??
function toggle(target, milliseconds)
{
setTimeout(function() {
var artz = document.getElementsByClassName('showhidemenu');
var targ = document.getElementById(target);
var isVis = targ.style.display=='block';
// hide all
for(var i=0;i<artz.length;i++)
{
artz[i].style.display = 'none';
}
// toggle current
targ.style.display = isVis?'none':'block';
return false;
}, milliseconds);
}

Javascript AddtoCart code not working

I am trying to create essentially a bot that can add a product on Foot Action to my cart. I have this code but it does not work. Can anybody debug it and just explain what I've done incorrectly. My browser is Chrome and I use TamperMonkey.
This an example of the product page:
Footaction product
window.addEventListener('load'
, function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
looks like you are missing the last closing squiggly bracket for window.load event
window.addEventListener('load', function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
}; // you were missing this line .. the ending squiggly bracket

Categories