Trying to cobble together some code to create a "Load More" button for a JSON array i'm pulling down and dynamically populating the page with, using the jquery slice method. Still terrible at jquery would appreciate any assistance with this. Thanks so much.
Code:
function populateButtons(data) {
var rightcontent = $(".rightcontent");
var sub = document.createElement("a");
var gh_buttons = $(".rightcontent a")
sub.innerHTML = data.title;
sub.setAttribute("href", data.absolute_url);
sub.setAttribute("target", "blank");
sub.setAttribute("class", "hidden");
$(rightcontent).append(sub);
setTimeout(function() {
$(gh_buttons).slice(0,10).removeClass("hidden");
}, 100);
}
var populateButtons = gh_loadMore;
gh_loadMore = function() {
var loadMore = function() {
$(rightcontent).after("<button>Load More</button>");
};
$(loadMore).on('click', function (e) {
e.preventDefault();
$(gh_buttons).slice(10, 10).slideDown();
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
};
gh_loadMore();
There is an order problem for your code, you can implement like following.
function populateButtons(data) {
var sub = document.createElement("a");
sub.innerHTML = data.title;
sub.setAttribute("href", data.absolute_url);
sub.setAttribute("target", "blank");
sub.setAttribute("class", "hidden");
$(".rightcontent").append(sub);
var gh_buttons = $(".rightcontent a");
setTimeout(function() {
$(gh_buttons).slice(0,10).removeClass("hidden");
}, 100);
}
var gh_loadMore = function() {
$(".rightcontent").after("<button id='btn'>Load More</button>");
};
populateButtons(yourdata); // call it with yourdata variable
gh_loadMore();
$("#btn").on('click', function (e) {
e.preventDefault();
$(".rightcontent a").slice(10, 20).removeClass("hidden");
$(".rightcontent a").slice(10, 20).slideDown();
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
Related
I create a function buttonEffects() with four button effects (one effect for each). Therefore, I would like to know how can I bring these variables outside of this function and fetch them into another function? I don't know whether I am able to do that, or I will need to recreate my code.!?
I already return each of the var on the botton of the function buttonEffects() such as return (var1, var2, var3, var4); and declare them outside of it but with no success.
//jQuery
$(document).ready(function() {
let blueBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
let redBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3');
let yellowBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3');
let greenBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3');
// VARIABLES - DOM QUERIES
const btnBlue = "#btnBlue";
const btnGreen = "#btnGreen";
const btnRed = "#btnRed";
const btnYellow = "#btnYellow";
const startButton = "#startButton";
const randomColors = ['blueButtonEffect', 'greenButtonEffect', 'redButtonEffect', 'yellowButtonEffect'];
console.log('blueButtonEffect');
//button effects
function buttonEffects() {
//button blue effect
var blueButtonEffect = $(btnBlue).click(function() {
var originalColor = $(this).css('background-color');
blueBtnAudio.play();
$(this).css('background-color', '#00FFFF');
setTimeout(function() {
$(btnBlue).css('background-color', originalColor);
}, 100);
});
//button green effect
var greenButtonEffect = $(btnGreen).click(function() {
var originalColor = $(this).css('background-color');
greenBtnAudio.play();
$(this).css('background-color', '#7FFF00');
setTimeout(function() {
$(btnGreen).css('background-color', originalColor);
}, 100)
});
// button red effect
var redButtonEffect = $(btnRed).click(function() {
var originalColor = $(this).css('background-color');
redBtnAudio.play();
$(this).css('background-color', '#F08080');
setTimeout(function() {
$(btnRed).css('background-color', originalColor)
}, 100);
});
// button yellow effect
var yellowButtonEffect = $(btnYellow).click(function() {
var originalColor = $(this).css('background-color');
yellowBtnAudio.play();
$(this).css('background-color', '#F0E68C');
setTimeout(function() {
$(btnYellow).css('background-color', originalColor)
}, 100);
});
}
// start the game
function startGame() { // it has a bug if clicked twice!
$(startButton).on('click', buttonEffects);
};
startGame();
function changeColor() {
//some code here?
}
});
Now I am trying a new approach where I live each variable out of the function scope and declare only its var names within the function buttonEffects()
to return the same startGame() effect.To be honest, I am pretty lost!
new approach:
//button blue effect
var blueButtonEffect = $(btnBlue).click(function() {
var originalColor = $(this).css('background-color');
blueBtnAudio.play();
$(this).css('background-color', '#00FFFF');
setTimeout(function() {
$(btnBlue).css('background-color', originalColor);
}, 100);
});
//button green effect
var greenButtonEffect = $(btnGreen).click(function() {
var originalColor = $(this).css('background-color');
greenBtnAudio.play();
$(this).css('background-color', '#7FFF00');
setTimeout(function() {
$(btnGreen).css('background-color', originalColor);
}, 100)
});
// button red effect
var redButtonEffect = $(btnRed).click(function() {
var originalColor = $(this).css('background-color');
redBtnAudio.play();
$(this).css('background-color', '#F08080');
setTimeout(function() {
$(btnRed).css('background-color', originalColor)
}, 100);
});
// button yellow effect
var yellowButtonEffect = $(btnYellow).click(function() {
var originalColor = $(this).css('background-color');
yellowBtnAudio.play();
$(this).css('background-color', '#F0E68C');
setTimeout(function() {
$(btnYellow).css('background-color', originalColor)
}, 100);
});
return (blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect);
// start the game
function buttonEffects() {
var blueButtonEffect;//something else shold be here....
var redButtonEffect;
var greenButtonEffect;
var yellowButtonEffect;
function startGame() { // it has a bug if clicked twice!
$(startButton).on('click', buttonEffects);
}
startGame();
}
});
Return an object, like this:
function thing() {
return {
item1: 1,
other: {
item2: 2,
item3: 3
}
};
}
var things = thing();
var item1 = things.item1;
var item2 = things.other.item2;
var item3 = things.other.item3;
I find a way that may right if it is wrong please let me know.
function buttonEffects(){
var blueButtonEffect = code here;
var redButtonEffect = code here;
var greenButtonEffect = code here;
var yellowButtonEffect = code here;
return {
item1: blueButtonEffect,
item2: redButtonEffect,
item3: greenButtonEffect,
item4: yellowButtonEffect
};
}
var effects = buttonEffects();
var blueButtonEffect2 = effects.item1;
var redButtonEffect2 = effects.item2;
var greenButtonEffect2 = effects.item3;
var yellowButtonEffect2 = effects.item4;
I got a problem that wastes more and more time. Now I want to ask you guys to help me out. I really think it's not a big thing but I can't find the solution:
I have two code snippets, both really similar:
$(function () {
$('.plus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal)) {
$qty.val(currentVal + 1);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
var timeout = setTimeout(function () {
$.overlay.open();
form.submit();
}, 2000);
});
}
});
$('.minus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal) && currentVal > 0) {
$qty.val(currentVal - 1);
window.clearTimeout(timeout);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
$.overlay.open({
closeOnClick: false
});
form.submit();
}, 2000);
});
}
});
});
I just want to reset the timeout after a click on one of the buttons.
var time;
}, 2000); use this-> }, time);
$(".test").on("click", function(){
time = 0;
});
I am trying to scroll the page to DIV, whose ID is sent through QueryString. The HTML content of the page is loaded from the Server side in SharePoint 2010.
I have used setTimeout() to wait until the content is loaded on the page and after timeout I am applying logic to scroll to div. But The page is not scrolling. Code is as below:
ExecuteOrDelayUntilScriptLoaded(getThankyouMsg, 'sp.js');
function getThankyouMsg() {
var fid = getQueryStringParameter("fid");
setTimeout(function () {
//window.location.href = window.location.href.split('?')[0] + "#" + fid;
jQuery('html, body').animate({
scrollTop: jQuery("#" + fid).offset().top
}, 2000);
}, 7000);
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
Can you please suggest what I am missing?
Thanks in advance.
I find solution for my question. We can use simple JavaScript instead of jQuery animate function.
ExecuteOrDelayUntilScriptLoaded(getThankyouMsg, 'sp.js');
function getThankyouMsg() {
var fid = getQueryStringParameter("fid");
setTimeout(function () {
location.hash = "#"+fid; //This line will navigates to Div ID
}, 7000);
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
Location.Hash = "#divId"
will work to scroll down to particular div on the page.
There's no need to write your own function to wait for the page to load. There is a jQuery function for that: .ready()
Your scrolling code seems to work fine with dummy code. This might work a bit better for you:
$(document).ready(function() {
getThankyouMsg();
});
function getThankyouMsg() {
var fid = getQueryStringParameter("fid");
jQuery('html, body').animate({
scrollTop: jQuery("#" + fid).offset().top
}, 2000);
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
That is assuming that getQueryStringParameter returns the correct value. There's no way for me to know this since it depends on your backend and the URL being used.
I create plugin something like this
timer plugin
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.getTimer();
}, 1000);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
and I call the plugin like this.
$(".myTimer").timer({
seconds : 100
});
i called the plugin at timerpage.php. When i changed the page to xxx.php by clicking another menu, the timer interval is still running and i need to the clear the timer interval.
i created a webpage using jquery ajax load. so my page was not refreshing when i change to another menu.
my question is, how to clear the timer interval or destroy the plugin when i click another menu?
Please try with following modifications:
timer plugin:
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.setTimer();
}, 1000);
$this.data("timerIntvalReference", timerIntval); //saving the timer reference for future use
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
Now in some other JS code which is going to change the div content
var intervalRef = $(".myTimer").data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef); //clear the old interval reference
//code to change the div content on menu change
For clearing timer associated with multiple DOM element, you may check below code:
//iterate ovel all timer element:
$("h3[class^=timer]").each(function(){
var intervalRef = $(this).data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef);
});
Hope this will give an idea to deal with this situation.
Instead of var timerIntval; set the variable timerInterval on the window object, then you will have the access this variable until the next refresh.
window.timerIntval = setInterval(function() {
Then when the user clicks on any item menu you can clear it:
$('menu a').click(function() {
clearInterval(window.timerIntval);
});
Live example (with multiple intervals)
$('menu a').click(function(e) {
e.preventDefault();
console.log(window.intervals);
for (var i = 0; i < window.intervals.length; i++) {
clearInterval(window.intervals[i]);
}
});
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
if (!window.intervals) {
window.intervals = [];
}
var intervalId = -1;
var seconds = options.seconds;
var $this = $(this);
var Timer = {
setTimer : function() {
clearInterval(intervalId);
if(seconds <= 0) {
alert("timeout");
} else {
intervalId = setInterval(function(){
//Timer.getTimer();
return Timer.getTimer();
}, 1000);
window.intervals.push(intervalId);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
$(".myTimer").timer({
seconds : 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<menu>
Menu 1
</menu>
<div class="myTimer"></div>
<div class="myTimer"></div>
Just notice that it's little bit risky because you can only run it once otherwise the interval id of the second will override the first.
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