Javascript - Run once per session - javascript

I would like the code below to execute only once when the website first loads.
I tried it with cookies and sessionstorage. But I have never found the right solution. Maybe it was wrong. Does anyone have an idea how I can solve that with session storage? I've never done anything with it. maybe something like this? :
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}
Any help will be appreciated. Thank You.
var my_div;
topIgnore = 100; // (in pixel units) used for function ignoreTop
window.onload = function() {
my_div = document.getElementById('my_div');
var my_div_style = window.getComputedStyle(my_div);
var width_div = parseInt(my_div_style.width, 10); // remove 'px' from string
var height_div = parseInt(my_div_style.height, 10);
// make sure the property exists, else you can get a NaN
my_div.style.left = 0;
my_div.style.top = 0;
// event
window.onmousemove = function(e) {
// my_div.innerHTML = e.pageX +' - '+ (leftBorder + width_div) +' - '+ width_div;
cursorIsInsideDiv(e);
}
// TO DO: feel free to make similar functions for left/right/bottom
// removes the first 100px
function ignoreTop(top) {
if(top < topIgnore) {
return topIgnore;
}
return top;
}
function cursorIsInsideDiv(e) {
var leftBorder = parseInt(my_div.style.left, 10); // remove 'px' from string
var topBorder = parseInt(my_div.style.top, 10);
// move left
if( e.pageX < leftBorder ) {
my_div.style.left = e.pageX + 'px';
}
// move right
else if( e.pageX > (leftBorder + width_div)) {
my_div.style.left = (e.pageX - width_div ) + 'px';
}
// move up
if( e.pageY < topBorder ) {
var top = e.pageY ;
top = ignoreTop(top);
my_div.style.top = top + 'px';
}
// move down
else if( e.pageY > (topBorder + height_div)) {
my_div.style.top = (e.pageY - height_div ) + 'px';
}
}
}
#my_div {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#my_div {
width: 300px;
height: 150px;
background: #ff0000;
position: absolute;
}
<div id="my_div">
<h2>Newsletter</h2>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email"><br>
</div>

Use JS to set a cookie:
document.cookie = "alreadyClicked=1; expires=Fri, 13 Jan 2017 20:00:00 UTC";
Then, you can check if it exists by defining a function to find the value (from http://www.w3schools.com/js/js_cookies.asp):
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if (getCookie("alreadyClicked") == "1") {
// do stuff if already clicked
} else {
// prompt for click?
}

I just inserted the code between. It worked. Corrected if that is wrong.
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}

Related

Prevent block from touching the containers borders

I have this little block that I move around using javascript code. It works all good except if I keep moving it, it can easily get out of the box where it is supposed to be.
Can I prevent this somehow? So no matter how far I want to move it, it will stay stuck inside of the container/box ?
Here's my snippet code:
/// store key codes and currently pressed ones
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
/// store reference to character's position and element
var character = {
x: 100,
y: 100,
speedMultiplier: 2,
element: document.getElementById("character")
};
var is_colliding = function(div1, div2) {
var d1_height = div1.offsetHeight;
var d1_width = div1.offsetWidth;
var d1_distance_from_top = div1.offsetTop + d1_height;
var d1_distance_from_left = div1.offsetLeft + d1_width;
var d2_height = div2.offsetHeight;
var d2_width = div2.offsetWidth;
var d2_distance_from_top = div2.offsetTop + d2_height;
var d2_distance_from_left = div2.offsetLeft + d2_width;
var not_colliding =
d1_distance_from_top <= div2.offsetTop ||
div1.offsetTop >= d2_distance_from_top ||
d1_distance_from_left <= div2.offsetTop ||
div1.offsetLeft >= d2_distance_from_left;
return !not_colliding;
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-5, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(5, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -5);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 5);
}
};
/// update current position on screen
moveCharacter();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
body{
display: flex;
justify-content: center;
align-items: center;
}
#character {
position: absolute;
width: 42px;
height: 42px;
background: red;
z-index:99;
}
#container{
width: 400px;
height: 400px;
background: transparent;
border:5px solid rgb(0, 0, 0);
position: relative;
overflow: hidden;
}
<div id="container">
<div id="character"></div>
</div>
PS: You can move the box using keyboard arrows.
Get the container width and height into variable and set a condition on your move
var moveCharacter = function(dx, dy){
let div_width = document.getElementById('container').clientWidth;
let div_height = document.getElementById('container').clientHeight;
if((div_width - character.x) < 50 ){ // 50 = width of character and padding
character.x = div_width - 50;
}
if(character.x < 10){ // Padding
character.x = 11;
}
if((div_height - character.y) < 50 ){
character.y = div_height - 50;
}
if(character.y < 10){
character.y = 11;
}

setInterval wont work if timing is too short

I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>

Compare two element position (offset)

I need to compare two elements offset positions to find whether one element is placed above on other element.
here i need to check the me is placed on the screen or not by using offset positions.
HTML Code
<div id="screen" style="background-color: olive; height: 120px; width:120px;"></div>
<span id="me" style="position: absolute; left: 44px; top: 86px;">me</span></div>
JavaScript
var a = document.getElementById('screen')
var b = document.getElementById('me');
aOffsetLeft=a.offsetLeft;
aOffsetTop=a.offsetTop;
bOffsetLeft=b.offsetLeft;
bOffsetTop=b.offsetTop;
//Here need to check whether b within a
Please help me
Above code is in jquery, below is javascript code :
https://jsfiddle.net/7xudznea/11/
var a = document.getElementById('screen')
var b = document.getElementById('me');
var c = document.getElementById('abc');
aOffsetLeft = a.offsetLeft;
aOffsetTop = a.offsetTop;
aoffsetHeight = a.offsetHeight;
aoffsetoffsetWidth = a.offsetoffsetWidth;
bOffsetLeft = b.offsetLeft;
bOffsetTop = b.offsetTop;
if ((aoffsetHeight + aOffsetTop >= bOffsetTop) || (aoffsetoffsetWidth + aOffsetLeft >= bOffsetLeft)) {
document.getElementById('abc').innerHTML = 'true';
} else {
document.getElementById('abc').innerHTML = 'false';
}
var $screen = $('#screen');
var $me = $('#me');
if ((($screen.height() + $screen.offset().top) >= $me.offset().top) || ($screen.width() + $screen.offset().left >= $me.offset().left)) {
return true;
} else {
return false;
}
Demo: https://jsfiddle.net/7xudznea/6/

Need Help Getting Floating Social Bar Working

My client is using the "Digg-Digg" plugin on their blog, and has asked me to implement the same thing on the rest of the site. I have copied the html code, the css file & the JS file, updated the links and variables, yet it still won't appear on the page. Can anyone help me out??? Thank you in advance.
Here is the html code:
<a id="dd_end"></a>
<div class='dd_outer'>
<div class='dd_inner'>
<div id='dd_ajax_float' style="position: absolute; top: 308px; left: -95px; display: block;">
<div class='dd_button_v'>
<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.scottera.com/" data-count="vertical" data-text="Arch Kit" data-via="archkit" ></a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_v'><script src="//connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://www.scottera.com" send="false" show_faces="false" layout="box_count" width="50" ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.scottera.com/'></g:plusone></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 40;var dd_top_offset_from_content = 0;var dd_override_start_anchor_id = "";var dd_override_top_offset = "";</script><script type="text/javascript" src="include/digg-digg/js/diggdigg-floating-bar.js?ver=5.3.6"></script>
And here is the CSS for the main sections:
.dd_outer {
width:100%;
height:0;
position:absolute;
top:0;
left:0;
z-index:9999
}
.dd_inner {
margin:0 auto;
position:relative
}
EDIT: Adding JS code:
var dd_top = 0;
var dd_left = 0;
jQuery(document).ready(function(){
var $floating_bar = jQuery('#dd_ajax_float');
var dd_anchorId = 'dd_start';
if ( typeof dd_override_start_anchor_id !== 'undefined' && dd_override_start_anchor_id.length > 0 ) {
dd_anchorId = dd_override_start_anchor_id;
}
var $dd_start = jQuery( '#' + dd_anchorId );
var $dd_end = jQuery('#dd_end');
var $dd_outer = jQuery('.dd_outer');
// first, move the floating bar out of the content to avoid position: relative issues
$dd_outer.appendTo('#wrapper');
if ( typeof dd_override_top_offset !== 'undefined' && dd_override_top_offset.length > 0 ) {
dd_top_offset_from_content = parseInt( dd_override_top_offset );
}
dd_top = parseInt($dd_start.offset().top) + dd_top_offset_from_content;
if($dd_end.length){
dd_end = parseInt($dd_end.offset().top);
}
dd_left = -(dd_offset_from_content + 55);
dd_adjust_inner_width();
dd_position_floating_bar(dd_top, dd_left);
$floating_bar.fadeIn('slow');
if($floating_bar.length > 0){
var pullX = $floating_bar.css('margin-left');
jQuery(window).scroll(function () {
var scroll_from_top = jQuery(window).scrollTop() + 30;
var is_fixed = $dd_outer.css('position') == 'fixed';
if($dd_end.length){
var dd_ajax_float_bottom = dd_end - ($floating_bar.height() + 30);
}
if($floating_bar.length > 0)
{
if(scroll_from_top > dd_ajax_float_bottom && $dd_end.length){
dd_position_floating_bar(dd_ajax_float_bottom, dd_left);
$dd_outer.css('position', 'absolute');
}
else if ( scroll_from_top > dd_top && !is_fixed )
{
dd_position_floating_bar(30, dd_left);
$dd_outer.css('position', 'fixed');
}
else if ( scroll_from_top < dd_top && is_fixed )
{
dd_position_floating_bar(dd_top, dd_left);
$dd_outer.css('position', 'absolute');
}
}
});
}
// Load Linked In Sharers (Resolves issue with position on page)
if(jQuery('.dd-linkedin-share').length){
jQuery('.dd-linkedin-share div').each(function(index) {
var $linkedinSharer = jQuery(this);
var linkedinShareURL = $linkedinSharer.attr('data-url');
var linkedinShareCounter = $linkedinSharer.attr('data-counter');
var linkedinShareCode = jQuery('<script>').attr('type', 'unparsed-IN/Share').attr('data-url', linkedinShareURL).attr('data-counter', linkedinShareCounter);
$linkedinSharer.html(linkedinShareCode);
IN.Event.on(IN, "systemReady", function() {
$linkedinSharer.children('script').first().attr('type', 'IN/Share');
IN.parse();
});
});
}
});
jQuery(window).resize(function() {
dd_adjust_inner_width();
});
var dd_is_hidden = false;
var dd_resize_timer;
function dd_adjust_inner_width() {
var $dd_inner = jQuery('.dd_inner');
var $dd_floating_bar = jQuery('#dd_ajax_float')
var width = parseInt(jQuery(window).width() - (jQuery('#dd_start').offset().left * 2));
$dd_inner.width(width);
var dd_should_be_hidden = (((jQuery(window).width() - width)/2) < -dd_left);
var dd_is_hidden = $dd_floating_bar.is(':hidden');
if(dd_should_be_hidden && !dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeOut(); }, -dd_left);
}
else if(!dd_should_be_hidden && dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeIn(); }, -dd_left);
}
}
function dd_position_floating_bar(top, left, position) {
var $floating_bar = jQuery('#dd_ajax_float');
if(top == undefined) top = 0 + dd_top_offset_from_content;;
if(left == undefined) left = 0;
if(position == undefined) position = 'absolute';
$floating_bar.css({
position: position,
top: top + 'px',
left: left + 'px'
});
}
You can use the floating social bar plugin
http://wordpress.org/plugins/floating-social-bar/ (it is my plugin)
There is an option to manually add the floating bar on all WordPress pages if you want. Just look at the code on the FAQ page.

Javascript Custom Scrollbar Bug

var start_mouse_y = 0;
var scroll_offset = 0;
function SET_SCROLL(e){
document.getElementById("online_list_scroll").draggable = true;
start_mouse_y = e.clientY;
}
function ADJUST_SCROLL(e){
dont_pass = (412 - set_scroll_height);
mouse_y = e.clientY;
scroll_top = parseInt(document.getElementById("online_list_scroll").style.top);
scroll_offset = (mouse_y - scroll_top) + 46;
new_top = scroll_top + (mouse_y - start_mouse_y);
document.getElementById("DEBUG").innerHTML = "my: "+mouse_y+"<br>new_top: "+new_top+"<br>scroll_offset: "+scroll_offset+"<br>scroll_top: "+scroll_top;
if(new_top <= 0){
document.getElementById("online_list_scroll").style.top = 0+"px";
}else if(new_top >= dont_pass){
document.getElementById("online_list_scroll").style.top = dont_pass+"px";
}else{
document.getElementById("online_list_scroll").style.top = new_top+"px";
}
scroll_bottom = set_scroll_height + new_top;
scroll_percent = scroll_bottom / 412;
online_show = (document.getElementById("online_list").scrollHeight - 412) * scroll_percent;
online_show = Math.round(online_show);
document.getElementById("online_list").scrollTop = online_show;
}
var SCROLL_ON = 0;
document.onmouseup = function(){ SCROLL_ON = 0; };
document.onmousemove = function(event){ if(SCROLL_ON == 1){ADJUST_SCROLL(event);} };
javascript ^^
<div style="float: left; width: 13px; position: relative; height: 412px;">
<div id="online_list_scroll" style="width: 5px; position: absolute; top: 0px; left: 4px; border-radius: 4px; background-color: #3f3f3f; height: 15px;" onmousedown="if(SCROLL_ON == 0){ SET_SCROLL(event); SCROLL_ON = 1; }"></div>
</div>
html^^
i dont know why but the scroll bar scrolls at a very fast and unsteady flow rate. it works, but just jerks when scrolls up and down, jerk as in as u move one way it shoots that way quicker and quicker.
Thanks for any help, worked figuring out how to do this all night.
You have a problem with local var the following code works. Not made as a general thing, just repaired the code. Here you have the code with the comments where is the common mistake.
//first make sure you have defined with var the variables you need.
var start_mouse_y = 0;
var mouse_y = 0;
var scroll_offset = 0;
function SET_SCROLL(e) {
document.getElementById("online_list_scroll").draggable = true;
start_mouse_y = e.clientY;
// you need mouse_y to be initialized with start_mouse_y
mouse_y = start_mouse_y;
}
function ADJUST_SCROLL(e) {
var set_scroll_height = 0;
var dont_pass = (412 - set_scroll_height);
// here you set the last mouse_y to be start_mouse_y or else it would be
// a the first position of the mouse ( eg. 8 ) subtracted from the current ( eg. 50 )
// now remembering the last already added position (eg. 49) which is subtracted from
// the current (eg. 50 ) it works just fine
start_mouse_y = mouse_y;
mouse_y = e.clientY;
var scroll_top = parseInt(document.getElementById("online_list_scroll").style.top);
scroll_offset = (scroll_top- mouse_y ) + 46;
var new_top = scroll_top + (mouse_y- start_mouse_y);
console.log("my: " + mouse_y + "<br>new_top: " + new_top + "<br>scroll_offset: " + scroll_offset + "<br>scroll_top: " + scroll_top);
if(new_top <= 0) {
document.getElementById("online_list_scroll").style.top = 0 + "px";
} else if(new_top >= dont_pass) {
document.getElementById("online_list_scroll").style.top = dont_pass + "px";
} else {
document.getElementById("online_list_scroll").style.top = new_top + "px";
}
var scroll_bottom = set_scroll_height + new_top;
var scroll_percent = scroll_bottom / 412;
var online_show = (document.getElementById("online_list").scrollHeight - 412) * scroll_percent;
online_show = Math.round(online_show);
document.getElementById("online_list").scrollTop = online_show;
}
var SCROLL_ON = 0;
document.onmouseup = function() {
SCROLL_ON = 0;
};
document.onmousemove = function(event) {
if(SCROLL_ON == 1) {ADJUST_SCROLL(event);
}
};
Best regards,

Categories

Resources