generating a number of divs at a time in jQuery - javascript

I'm trying to make a game with jquery where bullets are appended using a function. So far bullets are generating whenever I press spacebar but I want to generate bullets like 3-5 stacks. 3-5 bullets will be generated and then a short break then again 3-5 bullets will be generated and the process continues. Bullets are appended as div element. Here are the codes,
function generateBullet() {
var Player = $('#player');
var PlayerLeft = Player.offset().left;
var PlayerTop = Player.offset().top - 50;
var appendingValue = "<div class='bulletID' style=' position: absolute; left: 250px; top: 250px;'></div>";
var appendSize = $('.bulletID').size();
if (appendSize >= 3) {
$('#content').delay(5000).append(appendingValue);
} else {
$('#content').append(appendingValue);
}
}
function animateBullet() {
var bulletID = $('.bulletID');
bulletID.each(function () {
var nowTop = $(this).offset().top;
$(this).css("top", nowTop - 25);
});
}
var keys = {}
$(document).keydown(function (e) {
keys[e.keyCode] = true;
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
function shoot() {
var Player = $('#player');
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
generateBullet();
}
}
}
JSFIDDLE DEMO : http://jsfiddle.net/ygz5wo7r/1/
I'm not getting any more idea how to do this. Your help will be really appreciated. TnQ.

Try this
I added
return false;
after
if (appendSize >= 3) {
...
and
parseInt($(this).css("top"))< 0 && $(this).remove();
to animateBullet()
to remove the bullets when they leave the screen

you can count how many bullets you fired each chain, and block the gun if chain reaches 3-5 bullets. and then using a timeout you can unblock the gun. that way you have control over the interval between bullet chains:
Fixed Fiddle
var bullets_chain = 0;
var block_gun = false;
function generateBullet() {
if (block_gun == false) {
var Player = $('#player');
var PlayerLeft = Player.offset().left;
var PlayerTop = Player.offset().top - 50;
var appendingValue = "<div class='bulletID' style=' position: absolute; left: 250px; top: 250px;'></div>";
bullets_chain++;
if (bullets_chain >= 5) {
block_gun = true;
bullets_chain = 0;
setTimeout(function () {
block_gun = false;
}, 500);
}
$('#content').append(appendingValue);
}
}
function animateBullet() {
var bulletID = $('.bulletID');
bulletID.each(function () {
var nowTop = $(this).offset().top;
if (nowTop < 0) {
$(this).remove();
} else {
$(this).css("top", nowTop - 25);
}
});
}
var keys = {}
$(document).keydown(function (e) {
if (block_gun == false) {
keys[e.keyCode] = true;
}
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
function shoot() {
var Player = $('#player');
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
generateBullet();
}
}
}
$(document).ready(function () {
setInterval(shoot, 50);
setInterval(animateBullet, 100);
});

Related

Need help changing menu from hover to click

--- Original Hover code ---
function bind_dropdown() {
$('div#quick_nav div.search_dropdown').on('hover', function() {
var thisid = $(this).attr('id').split('_');
var this_action = thisid[1];
var this_width = 950;
var add_class = 'dropdown_full';
if(this_action == 4) {
this_width = 200;
add_class = 'dropdown_small';
}
if($('div#quick_nav div#dropdown_'+escape(this_action)).is(':visible')) {
$('div#quick_nav div#dropdown_'+escape(this_action)).addClass(add_class).slideUp(100);
}
else{
$('div#quick_nav div.dropdown').hide();
$('div#quick_nav div#dropdown_'+escape(this_action)).addClass(add_class).slideDown(100).width(this_width);
}
return false;
});
}
--- End Original Code ---
I did try and change hover to click. It works however to close the menu you now have to click on the menu icon again. Any help would be greatly appreciated. I would like to be able to click to show menu and when the mouse moves off the menu it would close automatically.
Thank you in advance
J
Use the below code
function bind_dropdown() {
$('div#quick_nav div.search_dropdown').on('click', function() {
var thisid = $(this).attr('id').split('_');
var this_action = thisid[1];
var this_width = 950;
var add_class = 'dropdown_full';
if(this_action == 4) {
this_width = 200;
add_class = 'dropdown_small';
}
if($('div#quick_nav div#dropdown_'+escape(this_action)).is(':visible')) {
$('div#quick_nav div#dropdown_'+escape(this_action)).addClass(add_class).slideUp(100);
}
return false;
}).on("mouseleave", function() {
var thisid = $(this).attr('id').split('_');
var this_action = thisid[1];
var this_width = 950;
var add_class = 'dropdown_full';
if(this_action == 4) {
this_width = 200;
add_class = 'dropdown_small';
}
$('div#quick_nav div.dropdown').hide();
$('div#quick_nav div#dropdown_'+escape(this_action)).addClass(add_class).slideDown(100).width(this_width);
});
}

How to replicate a typing effect using jQuery/JavaScript?

How to have the exact typing effect used on this page? https://www.braintreepayments.com/
<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']">Ve</span>
Here is the JSFiddle with the extracted library from the website : http://jsfiddle.net/8g6dsp0p/1/
You can initialize the script with this following code :
<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']"></span>
<script>
$(document).ready(function() {
new Writer
});
</script>
var word = "Venmo";
var cur = 1;
var intrvl = setInterval(function () {
$('.writer').html(word.slice(0,cur));
if(cur >= word.length) {
clearInterval(intrvl);
}
else{
cur++;
}
}, 500);
JSBin
The above jsBin has the code you require. it is not neatly formatted but code is correct.
Again to reproduce the code
<span clas="writer"></span>
var words = ["Venmo", "alright", "done", "ok"];
var curWord = 0;
function writeWord(word, deleteWord) {
var cur;
if(deleteWord){
cur = deleteWord.length;
var delIntrvl = setInterval(function () {
if(!cur) {
clearInterval(delIntrvl);
if(curWord < (words.length - 1)) {
writeWord(words[++curWord],"");
}
else {//if you dont need continous looping remove this else statement
curWord = 0;
writeWord(words[curWord],"");
}
}
else{
var reqWrd = deleteWord.slice(0,cur);
console.log(reqWrd);
$('.writer').html(reqWrd);
cur--;
}
}, 200);
}
else {
cur=1;
var intrvl = setInterval(function () {
if(cur >= word.length) {
clearInterval(intrvl);
writeWord("",word);
}
else{
var reqWrd = word.slice(0,cur);
console.log(reqWrd);
$('.writer').html(reqWrd);
cur++;
}
}, 200);
}
}
writeWord(words[curWord], "");
Updating the code and also providing jsBin for continous looping
ContinousLoopJsBin

How can I get div to move up and down on hover? Mouseover and Mouseout conflict

I am trying to use run an animation using setInterval which works quiet well. Although I am trying to get the animation to run all the way through and then stop after mouse out.
I can get the div to move up and down but if you move the mouse in and out too fast it get's stuck in a loop of adding and subtracting pixels. Or other times it will stop moving altogether and get stuck at the top of bottom.
You can see the issue here, move the mouse in and out of the small box a few times fast.
https://jsfiddle.net/L16fdbrj/1/
Here is my Javascript:
var blog_folder_index = false;
var blog_folder_pos = 0;
var blog_folder_interval;
var framespeed = 5;
function blog_folder_mouseover()
{
if (blog_folder_index == false)
{
document.getElementById("blog_folder_button").style.cursor = "pointer";
blog_folder_interval = setInterval(function (){ blog_folder_add();}, 35);
}
}
function blog_folder_mouseout()
{
blog_folder_interval = setInterval(function (){ blog_folder_subtract();}, 50);
console.log("mouseout");
}
function blog_folder_add()
{
if (blog_folder_pos <= -30)
{
console.log(blog_folder_pos);
stop_function();
}
else if (blog_folder_pos > -30)
{
blog_folder_pos -= framespeed;
document.getElementById("blog_folder").style.marginTop = blog_folder_pos + 'px ';
}
}
function blog_folder_subtract()
{
if (blog_folder_pos >= 0)
{
console.log(blog_folder_pos);
stop_function();
}
else if (blog_folder_pos < 0)
{
blog_folder_pos += framespeed;
document.getElementById("blog_folder").style.marginTop = blog_folder_pos + 'px ';
}
}
function blog_folder_click()
{
blog_folder_index = true;
portfolio_folder_index = false;
about_folder_index = false;
document.getElementById("blog_folder_button").style.cursor = "default";
document.getElementById("portfolio_folder").style.zIndex = "2";
document.getElementById("blog_folder").style.zIndex = "3";
document.getElementById("about_folder").style.zIndex = "1";
blog_folder_interval = setInterval(function (){ blog_folder_subtract();}, 35);
}
function stop_function()
{
clearInterval(blog_folder_interval);
}
You simply need to clear your previous interval before creating a new one:
https://jsfiddle.net/L16fdbrj/2/
function blog_folder_mouseover() {
if (blog_folder_index == false) {
document.getElementById("blog_folder_button").style.cursor = "pointer";
// clear previous interval
stop_function();
blog_folder_interval = setInterval(function () {
blog_folder_add();
}, 35);
}
}
function blog_folder_mouseout() {
// clear previous interval
stop_function();
blog_folder_interval = setInterval(function () {
blog_folder_subtract();
}, 50);
console.log("mouseout");
}

Hover to click in wordpress menu

I used a theme that I changed to show sub menu horizontally, now I want to show sub menu onClick and not on hover, I'm not good at javascript but I think that this code is about the navigation menu:
var nav = {
init: function() {
// Add parent class to items with sub-menus
jQuery("ul.sub-menu").parent().addClass('parent');
var menuTop = 40;
var menuTopReset = 80;
// Enable hover dropdowns for window size above tablet width
jQuery("nav").find(".menu li.parent").hoverIntent({
over: function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
// Setup menuLeft variable, with main menu value
var subMenuWidth = jQuery(this).find('ul.sub-menu').first().outerWidth(true);
var mainMenuItemWidth = jQuery(this).outerWidth(true);
var menuLeft = '-' + (Math.round(subMenuWidth / 2) - Math.round(mainMenuItemWidth / 2)) + 'px';
var menuContainer = jQuery(this).parent().parent();
// Check if this is the top bar menu
if (menuContainer.hasClass("top-menu")) {
if (menuContainer.parent().parent().parent().hasClass("top-bar-menu-right")) {
menuLeft = "";
} else {
menuLeft = "-1px";
}
menuTop = 30;
menuTopReset = 40;
} else if (menuContainer.hasClass("header-menu")) {
menuLeft = "-1px";
menuTop = 28;
menuTopReset = 40;
} else if (menuContainer.hasClass("mini-menu") || menuContainer.parent().hasClass("mini-menu")) {
menuTop = 40;
menuTopReset = 58;
} else {
menuTop = 44;
menuTopReset = 64;
}
// Check if second level dropdown
if (jQuery(this).find('ul.sub-menu').first().parent().parent().hasClass("sub-menu")) {
menuLeft = jQuery(this).find('ul.sub-menu').first().parent().parent().outerWidth(true) - 2;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', menuTop);
}
},
out:function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', menuTopReset);
}
}
});
jQuery(".shopping-bag-item").live("mouseenter", function() {
var subMenuTop = 44;
if (jQuery(this).parent().parent().hasClass("mini-menu")) {
subMenuTop = 40;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', subMenuTop);
}).live("mouseleave", function() {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', 64);
}
});
// Toggle Mobile Nav show/hide
jQuery('a.show-main-nav').on('click', function(e) {
e.preventDefault();
if (jQuery('#main-navigation').is(':visible')) {
jQuery('.header-overlay .header-wrap').css('position', '');
} else {
jQuery('.header-overlay .header-wrap').css('position', 'relative');
}
jQuery('#main-navigation').toggle();
});
jQuery(window).smartresize(function(){
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
var menus = jQuery('nav').find('ul.menu');
menus.each(function() {
jQuery(this).css("display", "");
});
}
});
// Set current language to top bar item
var currentLanguage = jQuery('li.aux-languages').find('.current-language span').text();
if (currentLanguage !== "") {
jQuery('li.aux-languages > a').text(currentLanguage);
}
},
hideNav: function(subnav) {
setTimeout(function() {
if (subnav.css("opacity") === "0") {
subnav.css("display", "none");
}
}, 300);
}
};
I tried to replace "hoverIntent" by "click" but it doesn't work, what can I do?
What's happening when someone currently hovers, it does one thing while hovering and when they leave it has to d a sort of cleanup which are the two functions within hoverintent, namely over and out so the code would need to be split into two event listeners one for click of the element and one for blur
I have chained the two listeners to the inital selector so it should all work.
var nav = {
init: function() {
// Add parent class to items with sub-menus
jQuery("ul.sub-menu").parent().addClass('parent');
var menuTop = 40;
var menuTopReset = 80;
// Enable click dropdowns for window size above tablet width
jQuery("nav").find(".menu li.parent").on('click', function (event) {
if($(event.target).parent().hasClass('menu-item-has-children')){
event.preventDefault();
};
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
// Setup menuLeft variable, with main menu value
var subMenuWidth = jQuery(this).find('ul.sub-menu').first().outerWidth(true);
var mainMenuItemWidth = jQuery(this).outerWidth(true);
var menuLeft = '-' + (Math.round(subMenuWidth / 2) - Math.round(mainMenuItemWidth / 2)) + 'px';
var menuContainer = jQuery(this).parent().parent();
// Check if this is the top bar menu
if (menuContainer.hasClass("top-menu")) {
if (menuContainer.parent().parent().parent().hasClass("top-bar-menu-right")) {
menuLeft = "";
} else {
menuLeft = "-1px";
}
menuTop = 30;
menuTopReset = 40;
} else if (menuContainer.hasClass("header-menu")) {
menuLeft = "-1px";
menuTop = 28;
menuTopReset = 40;
} else if (menuContainer.hasClass("mini-menu") || menuContainer.parent().hasClass("mini-menu")) {
menuTop = 40;
menuTopReset = 58;
} else {
menuTop = 44;
menuTopReset = 64;
}
// Check if second level dropdown
if (jQuery(this).find('ul.sub-menu').first().parent().parent().hasClass("sub-menu")) {
menuLeft = jQuery(this).find('ul.sub-menu').first().parent().parent().outerWidth(true) - 2;
}
jQuery(this).find('ul.sub-menu').first().addClass('show-dropdown').css('top', menuTop);
}
}).on('mouseleave',function () {
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
jQuery(this).find('ul.sub-menu').first().removeClass('show-dropdown').css('top', menuTopReset);
}
});
// Toggle Mobile Nav show/hide
jQuery('a.show-main-nav').on('click', function(e) {
e.preventDefault();
if (jQuery('#main-navigation').is(':visible')) {
jQuery('.header-overlay .header-wrap').css('position', '');
} else {
jQuery('.header-overlay .header-wrap').css('position', 'relative');
}
jQuery('#main-navigation').toggle();
});
jQuery(window).smartresize(function(){
if (jQuery('#container').width() > 767 || jQuery('body').hasClass('responsive-fixed')) {
var menus = jQuery('nav').find('ul.menu');
menus.each(function() {
jQuery(this).css("display", "");
});
}
});
// Set current language to top bar item
var currentLanguage = jQuery('li.aux-languages').find('.current-language span').text();
if (currentLanguage !== "") {
jQuery('li.aux-languages > a').text(currentLanguage);
}
},
hideNav: function(subnav) {
setTimeout(function() {
if (subnav.css("opacity") === "0") {
subnav.css("display", "none");
}
}, 300);
}
};
That seems overly complicated. Do you have a link to the live version?
Usually, when doing a click-to-see submenu with a clickable parent, I set a variable to see whether the menu is open, if not dont go to link. if so, go to link.
An example: http://codepen.io/jhealey5/pen/iLgom
var $handle = $('.sub-menu').prev();
var opened = 0;
$handle.on('click', function(e){
if (opened) {
window.location.href = $(this).attr('href');
} else {
e.preventDefault();
e.stopPropagation();
$('.sub-menu').slideToggle();
opened = 1;
}
});
$('html').on('click', function(){
if (opened) {
$('.sub-menu').slideToggle();
opened = 0;
}
});
Depending on that menu of yours, you could use something similar. But it's using a lot of code for a menu.

Splitting HTML page into different sections using sliding panel dividers? How is it done?

I'm wanting to divide a web page up into different sections as shown here. I'm trying to figure it out what this technique is called and an efficient way to implement it?
The page is divided up into different sections giving the user the flexiblity to expand and contract the different sections using panel handles.
I'm assuming these aren't regular frames (which I'd like to avoid using anyways).
Does anybody know of a tutorial or good example out there besides the one on jsfiddle?
the idea is quite simple.
you break up the screen with some elements, it does not really matter which (say divs) with a given height.
then attach a onclick event to the handle that starts the drag. what the onclick does is attach a mousemove event to the body which will resize the elements.
here is something i wrote a while back (before my jquery days), i'm sure it could be written much better, and you might find a plugin for this, i don't know of one:
function WidenHandle(widenedELement, handleElement, ondblClick, startWidth, withCoverDiv, onDrop)
{
this.Handle = handleElement;
this.IsClosed = false;
this.Element = widenedELement;
this.LastX = 0;
this.LastY = 0;
this.AttachedDragFunction = null;
this.AttachedDropFunction = null;
this.StartWidth = startWidth ? startWidth : 300;
this.CoverDiv;
this.OnDrop = onDrop;
this.IsDragging = false;
if (withCoverDiv)
{
var coverDiv = document.createElement("div");
coverDiv.style.width = "2000px";
coverDiv.style.height = "2000px";
coverDiv.style.display = "none";
coverDiv.style.position = "fixed";
coverDiv.style.zIndex = "1000";
// coverDiv.style.backgroundColor = "red";
// coverDiv.style.opacity = "0.3";
coverDiv.style.top = '0px';
this.CoverDiv = coverDiv;
document.body.appendChild(coverDiv);
}
if (this.Handle.addEventListener)
{
this.Handle.addEventListener("mousedown", function(element)
{
return function(event)
{
element.StartDragging(event);
if (element.CoverDiv)
element.CoverDiv.style.display = "";
if (event.preventDefault)
event.preventDefault();
}
} (this), true);
this.Handle.addEventListener("dblclick", function(element)
{
return function(event)
{
element.Close(event);
if (element.CoverDiv)
element.CoverDiv.style.display = "none";
ondblClick(element);
}
} (this), true);
}
else
{
this.Handle.attachEvent("onmousedown", function(element)
{
return function(event)
{
element.StartDragging(event);
if (element.CoverDiv)
element.CoverDiv.style.display = "";
if (event.preventDefault)
event.preventDefault();
}
} (this));
this.Handle.attachEvent("ondblclick", function(element)
{
return function(event)
{
element.Close(event);
if (element.CoverDiv)
element.CoverDiv.style.display = "none";
ondblClick(element);
}
} (this), true);
}
}
WidenHandle.prototype.StartDragging = function(event)
{
this.IsDragging = true;
if (this.CoverDiv)
this.CoverDiv.style.display = "none";
this.ClearAttachedEvents();
this.LastX = this.GetX(event);
// ** attach mouse move and mouse up events to document ** //
this.AttachedDragFunction = function(element)
{
return function(event)
{
element.OnDragging(event);
}
} (this);
this.AttachedDropFunction = function(element)
{
return function(event)
{
element.OnDropping(event);
}
} (this);
if (window.attachEvent) // ie
{
document.attachEvent('onmousemove', this.AttachedDragFunction);
document.attachEvent('onmouseup', this.AttachedDropFunction);
}
else // ff
{
document.onmousemove = this.AttachedDragFunction;
document.onmouseup = this.AttachedDropFunction;
}
}
// ** for repositioning popup while dragging ** //
WidenHandle.prototype.OnDragging = function(event)
{
clearHtmlSelection();
this.WidenCell(event);
}
// ** for release popup movement when dropping ** //
WidenHandle.prototype.OnDropping = function(event)
{
this.IsDragging = false;
if (this.CoverDiv)
this.CoverDiv.style.display = "none";
this.ClearAttachedEvents();
if (this.OnDrop)
this.OnDrop();
}
WidenHandle.prototype.ClearAttachedEvents = function()
{
// ** detach events from document ** //
if (window.attachEvent) // ie
{
document.detachEvent('onmousemove', this.AttachedDragFunction);
document.detachEvent('onmouseup', this.AttachedDropFunction);
}
else // ff
{
document.onmousemove = null;
document.onmouseup = null;
}
}
WidenHandle.prototype.GetX = function(event)
{
// ** return x position of mouse ** //
var posx = 0;
if (!event) event = window.event;
if (event.pageX)
{
posx = event.pageX;
}
else if (event.clientX)
{
posx = event.clientX;
}
return posx;
}
WidenHandle.prototype.WidenCell = function(event)
{
if (!this.Element.style.width)
this.Element.style.width = this.Element.offsetWidth - 9 + "px";
var width = parseInt(this.Element.style.width) + (this.GetX(event) - this.LastX);
if (width > 13)
this.Element.style.width = width + "px";
// ** remember last mouse position ** //
this.LastX = this.GetX(event);
}
WidenHandle.prototype.Close = function(event)
{
var width = parseInt(this.Element.style.width);
if (width < 30)
{
this.IsClosed = false;
this.Element.style.width = "";
return;
// width = this.StartWidth;
}
else
{
width = 14;
this.IsClosed = true;
}
this.Element.style.width = width + "px";
}
function clearHtmlSelection()
{
var sel;
if (document.selection && document.selection.empty)
{
document.selection.empty();
}
else if (window.getSelection)
{
sel = window.getSelection();
if (sel && sel.removeAllRanges) sel.removeAllRanges();
}
}

Categories

Resources