Disable onclick/mousedown on Div when being overlapped by another div - javascript

I have got a loop function that slides 2 divs over a 3rd. Working example can be found here: http://jsbin.com/OYebomEB/4/.
Main function:
var elements = ['#pointsbarDiv', '#hotlink1Div', '#pointsbarDiv', '#hotlink2Div'];
function hotlinks_loop(index) {
$(elements[index]).css({top: -75, display: 'block'}).animate({top: '+0'}, 3000, function () {
var $self = $(this);
var currentInstance = this;
setTimeout(function () {
$self.animate({top: $(window).height()}, 3000);
if(currentInstance.hotlinkStop !== true){
hotlinks_loop((index + 1) % elements.length);
}
}, 3000, currentInstance);
});
}
hotlinks_loop(0); // start with the first element
I have some code to disable onclick while hotlink divs are moving:
hotlink2BtnClick: function () {
if ($("#hotlink2Div").css("top") === "0px") {
//do stuff;
} else {
//do stuff;
}
},
However, for the stationary pointsbarDiv I cannot find a solution to disable onclick/mousedown while hotlink divs are sliding over it.
I have tried various 'If's like the the following example:
if (($("#hotlink1Div").css("top") < "76px" && $("#hotlink1Div").css("bottom") < "150px") || ($("#hotlink1Div").css("top") > "-75px" && $("#hotlink1Div").css("bottom") < "75px")))...
I am also wondering if there is way I can just disable onclick/mousedown while divs are moving within the main function provided.
I should mention that I am a newbie to javascript/jquery.

JQuery event functions get passed an event object - you can accept this in your function, and use it to stop propagation:
hotlink2BtnClick: function (ev) {
ev.stopPropagation();
http://api.jquery.com/event.stoppropagation/
Also, if you put your js examples on http://jsfiddle.net, then we can fork it and return it to you fixed.

I managed to do this by creating a an extra div giving it a z-index of -1 and setting visibility to hidden.
Then replacing the points div with this in array for the loop.
Followed by implementing a similar code solution hotlink2BtnClick().

Related

if else statement javascript to make div change color based on .scrollTop

I am a beginner coder and I'm trying to change the background color of a div based on how far down scrolled the webpage is, where am I going wrong?
Do I need to put in something to call the scrollTop amount?
(function () {
var scroll = .scrollTop;
if (scroll > 50) {
document.getElementByClassName("shop").style.backgroundColor = '#99C262';
}
else
{
document.getElementByClassName("shop").style.backgroundColor = ‘red’;
}
})();
Lose the dot, instead of “.shop” go for “shop”
And the actual function getElementsByClassName and it returns a collections of divs with the class name. But you need the first one (assuming you have only one such div) hence the 0 index in array
parentDOM.getElementsByClassName('test')[0].style.backgroundColor = "red";
<p class="test">hello here</p>
Many errors in the code....
var scrole = .scrollTop; not sure if you are trying to assign any value or is it window.scrollTop.
document.getElementByClassName(".shop") should be changed to document.getElementByClassName("shop")
else if (scroll < 50 ){ //statement } to be changed to else { //statement }
function is wrapped in small bracket but has never been invoked.
Self invoking function example :-
(function(){
console.log(Math.PI);
})();
Using a dot before a class name when getting it in javascript using getElementsByClassName is an Incorrect Syntax. Below is the correct syntax.
document.getElementsByClassName("shop")
Tip: Always Use the console window to monitor your Syntax and other errors.
Your code are only executed once if you don't attach a listener. Let me just use these code from MDN docs with a bit of edit. The docs
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
if (scroll_pos > 50) {
document.querySelector(“.shop”).style.backgroundColor = '#99C262';
} else if (scroll_post < 50) {
document.querySelecttor(“.shop”).style.backgroundColor = ‘red’;
} else {
// add more colorrrs!
}
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});

How to do car turn lights (blinkers) with jQuery?

I have some strange task to do. I have to implement car turning lights functionality into my web page. I have two buttons (left and right) and two green arrows (left and right). It should be that: I click left button (left arrow is now hidden) and left arrow should blink. When I click once more time, it should stop animation and be hidden. I just don't know to handle state of button and use it properly. Thanks.
$("#arrow-left").click(function blinker() {
if(something) {
$('#arrow-left-blink').css("visibility", "visible");
$('#arrow-left-blink').fadeOut(500);
$('#arrow-left-blink').fadeIn(500);
setInterval(blinker, 1000);
} else {
//hide
}
}
You should create a closure to save the state across different clicks. Simply create a closure by putting the click handler inside a self-invoking function and declare+initialize your shared variables inside it. Increase your count at the end of the click handler. You can toggle between true and false with the modulus operator '%'. 0%2==0, 1%2==1, 2%2==0, 3%2==1, 4%2==0, ...
(function(){
var counter = 0;
$("#arrow-left").click(function blinker() {
if(counter%2) {// modulus operator will toggle between 0 and 1 which corresponds to truthy or falsy
$('#arrow-left-blink').css("visibility", "visible");
$('#arrow-left-blink').fadeOut(500);
$('#arrow-left-blink').fadeIn(500);
setInterval(blinker, 1000);
} else {
//hide
}
counter++;
});
})();
You could define an outside variable counter.
For example:
$(document).ready(function() {
var counter = 0;
var blinking;
function blinker() {
$('#arrow-left-blink').fadeOut(500);
$('#arrow-left-blink').fadeIn(500);
blinker();
}
$("#arrow-left").click(function() {
counter++;
if (counter % 2 == 1) {
$('#arrow-left-blink').css("visibility", "visible");
blinking = setTimeout(function() {
blinker();
}, 1000);
} else {
clearInterval(blinking);
$('#arrow-left-blink').css("visibility", "hidden");
}
});
});
Here is a JSFiddle link: https://jsfiddle.net/o2xb8Lod/.
I would create a css class to handle the fading and blinking with css animations and just toggleClass on click in Jquery.

Close all Angular JS Bootstrap popovers with click anywhere on screen?

I am using the Angular directives for bootstrap.
I have a popover as in their example:
<button popover="Hello, World!" popover-title="Title" class="btn btn-default ng-scope">Dynamic Popover</button>
It closes when you click on the button again. I'd like to close it -- and any other open popovers -- when the user clicks anywhere.
I don't see a built-in way to do this.
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
if(popupElement[0].previousSibling!=e.target){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});
This feature request is being tracked (https://github.com/angular-ui/bootstrap/issues/618). Similar to aet's answer, you can do what is recommended in the feature request as a work-around:
$('body').on('click', function (e) {
$('*[popover]').each(function () {
//Only do this for all popovers other than the current one that cause this event
if (!($(this).is(e.target) || $(this).has(e.target).length > 0)
&& $(this).siblings('.popover').length !== 0
&& $(this).siblings('.popover').has(e.target).length === 0)
{
//Remove the popover element from the DOM
$(this).siblings('.popover').remove();
//Set the state of the popover in the scope to reflect this
angular.element(this).scope().tt_isOpen = false;
}
});
});
(source: vchatterji's comment in feature request mentioned above)
The feature request also has a non-jQuery solution as well as this plnkr: http://plnkr.co/edit/fhsy4V
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if (popups) {
for (var i = 0; i < popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
console.log(2);
if (popupElement[0].previousSibling != e.target) {
popupElement.scope().$parent.isOpen = false;
popupElement.scope().$parent.$apply();
}
}
}
});
What you say it's a default settings of the popover, but you can control it with the triggers function, by putting blur in the second argument of the trigger like this popover-trigger="{mouseenter:blur}"
One idea is you can change the trigger to use mouse enter and exit, which would ensure that only one popover shows at once. The following is an example of that:
<button popover="I appeared on mouse enter!"
popover-trigger="mouseenter" class="btn btn-default"
popover-placement="bottom" >Hello World</button>
You can see this working in this plunker. You can find the entire list of tooltip triggers on the angular bootstrap site (tooltips and popovers have the same trigger options). Best of luck!
Had the same requirement, and this is how we did it:
First, we modified bootstrap, in the link function of the tooltip:
if (prefix === "popover") {
element.addClass('popover-link');
}
Then, we run a click handler on the body like so:
$('body').on('click', function(e) {
var clickedOutside = true;
// popover-link comes from our modified ui-bootstrap-tpls
$('.popover-link').each(function() {
if ($(this).is(e.target) || $(this).has(e.target).length) {
clickedOutside = false;
return false;
}
});
if ($('.popover').has(e.target).length) {
clickedOutside = false;
}
if (clickedOutside) {
$('.popover').prev().click();
}
});
I am using below code for same
angular.element(document.body).popover({
selector: '[rel=popover]',
trigger: "click"
}).on("show.bs.popover", function(e){
angular.element("[rel=popover]").not(e.target).popover("destroy");
angular.element(".popover").remove();
});
Thank you Lauren Campregher, this is worked.
Your code is the only one that also runs the state change on the scope.
Only configured so that if you click on the popover, the latter closes.
I've mixed your code, and now also it works if you click inside the popover.
Whether the system, whether done through popover-template,
To make it recognizable pop up done with popover-template, I used classes popover- body and popover-title, corresponding to the header and the body of the popover made with the template, and making sure it is pointing directly at them place in the code:
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
var content;
var arrow;
if(popupElement.next()) {
//The following is the content child in the popovers first sibling
// For the classic popover with Angularjs Ui Bootstrap
content = popupElement[0].querySelector('.popover-content');
// For the templating popover (popover-template attrib) with Angularjs Ui Bootstrap
bodytempl = popupElement[0].querySelector('.popover-body');
headertempl= popupElement[0].querySelector('.popover-title');
//The following is the arrow child in the popovers first sibling
// For both cases.
arrow = popupElement[0].querySelector('.arrow');
}
if(popupElement[0].previousSibling!=e.target && e.target != content && e.target != arrow && e.target != bodytempl && e.target != headertempl){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});
Have ever a good day, thank you Lauren, thank you AngularJS, Thank You So Much Stack Family!
Updated:
I updated all adding extra control.
The elements within the popover were excluded from the control (for example, a picture inserted into the body of the popover.). Then clicking on the same closed.
I used to solve the command of API Node.contains, integrated in a function that returns true or false.
Now with any element placed inside, run the control, and keeps the popover open if you click inside :
// function for checkparent with Node.contains
function check(parentNode, childNode) { if('contains' in parentNode) { return parentNode.contains(childNode); } else { return parentNode.compareDocumentPosition(childNode) % 16; }}
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
var content;
var arrow;
if(popupElement.next()) {
//The following is the content child in the popovers first sibling
// For the classic popover with Angularjs Ui Bootstrap
content = popupElement[0].querySelector('.popover-content');
// For the templating popover (popover-template attrib) with Angularjs Ui Bootstrap
bodytempl = popupElement[0].querySelector('.popover-body');
headertempl= popupElement[0].querySelector('.popover-title');
//The following is the arrow child in the popovers first sibling
// For both cases.
arrow = popupElement[0].querySelector('.arrow');
}
var checkel= check(content,e.target);
if(popupElement[0].previousSibling!=e.target && e.target != content && e.target != arrow && e.target != bodytempl && e.target != headertempl&& checkel == false){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});

jQuery - hiding an element when on a certain page

I have this wizard step form that I simulated with <ul> list items by overlapping inactive <li> items with absolute positioning.
The wizard form is working as desired except that I want to hide next or previous button on a certain step.
This is my logic in jQuery but it doesn't do any good.
if (index === 0) {
$('#prev').addClass(invisible);
$('#prev').removeClass(visible);
} else if (index === 1) {
$('#prev').addClass(visible);
$('#prev').removeClass(invisible);
} else {
$('#next').addClass(invisible);
}
To get the index value I used eq() chained on a current step element like the following
var current;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.eq();
});
I tried to isolate it as much as possible but my full code will give you a better idea.
If you would care to assist please check my JS BIN
There were several issues
you used .eq instead of index
you were missing quotes around the class names
your navigation logic was flawed
no need to have two classes to change visibility
I believe the following is an improvement, but let me know if you have questions.
I added class="navBut" to the prev/next and rewrote the setting of the visibility
Live Demo
var current;
var navstep;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
setBut(current);
$('.navBut').on('click', function() {
var next = this.id=="next";
if (next) {
if (current.next().length===0) return;
current.next().addClass('current').show();
navstep.next().addClass('active');
}
else {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
navstep.prev().addClass('active');
}
current.removeClass('current').hide();
navstep.removeClass('active');
current = (next)?current.next():current.prev();
navstep = (next)?navstep.next():navstep.prev();
setBut(current);
});
});
function setBut(current) {
var index=current.index();
var max = current.parent().children().length-1;
$('#prev').toggleClass("invisible",index<1);
$('#next').toggleClass("invisible",index>=max);
}
The eq function will not give you the index, for that you need to use the index() function.
I have not looked at the whole code but shouldn't your class assignemnts look like:
$('#prev').addClass('invisible');
$('#prev').removeClass('visible');
i.e. with quotes around the class names? And is it really necessary to have a class visible? Assigning and removing the class invisible should easily do the job (provided the right styles have been set for this class).
You should make 4 modifications.
1) Use .index() instead of .eq();
2) Add a function changeIndex which changes the class depends on the index and call it on click of prev and next.
3) add quotes to invisible and visible
4) There is a bug in your logic, try going to 3rd step and come back to 1st step. Both buttons will disappear. So you have to make next button visible if index = 0
Here is the demo :
http://jsfiddle.net/ChaitanyaMunipalle/9SzWB/
Use index() function instead of eq() because eq() will return object and index() will return the integer value.
DEMO HERE
var current;
var navstep;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
}(jQuery));
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.index();
change_step(index)
});
$('#prev').on('click', function() {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
current.removeClass('current').hide();
navstep.prev().addClass('active');
navstep.removeClass('active');
current = current.prev();
navstep = navstep.prev();
index = current.index();
change_step(index)
});
function change_step(value)
{
if (value === 0) {
$('#prev').hide();
$('#next').show();
} else if (value === 1) {
$('#prev').show();
$('#next').show();
} else {
$('#next').hide();
$('#prev').show();
}
}

Getting all visible elements using MooTools

I am moving from jQuery to MooTools (for the fun..) and I have this line of code :
$subMenus = $headMenu.find('li ul.sub_menu:visible');
How I can write this in mootools?
I know that I can use getElements but How I can check for visible ul?(I am using this(:visible) selector a lot).
Edit -
I implemented my own function :
function findVisibleElements(elementsCollection){
var returnArray = [];
elementsCollection.each(function(el){
if(el.getStyle('display') === 'block'){
returnArray.push(el);
}
});
return returnArray;
}
And what i want is to slide up all the visible sub menu, this is what I wrote :
// Sliding up the visible sub menus
if( visibleSubMenus.length > 0 ){
visibleSubMenus.each(function(el){
var slider = new Fx.Slide(el, {duration: 2000});
slider.slideOut();
});
}
Why my code isn`t working?My function is working, and the problem is with the Fx.Slide.
I added mootools more with Fx.Slide.
Just extend the selector functionality - it's MooTools!
$extend(Selectors.Pseudo, {
visible: function() {
if (this.getStyle('visibility') != 'hidden' && this.isVisible() && this.isDisplayed()) {
return this;
}
}
});
After that just do the usual $$('div:visible') which will return the elements that are visible.
Check out the example I've created: http://www.jsfiddle.net/oskar/zwFeV/
The $$() function in Mootools is mostly equivalent to JQuery's $() does-it-all selector.
// in MooTools
var elements = $$('.someSelector');
// natively in most newer browsers
elements = document.body.querySelectorAll('.someSelector');
However, for this specific case since :visible isn't a real pseudo class, you'll have to approximate it using an Array filter in Mootools.
var isItemVisible = function (item) {
return item.style.visibility != 'hidden' && item.style.display != 'none';
}
var elements = $$('ul').filter(isItemVisible);
There might be other things that you consider make an item 'invisible', in which case you can add them to the filtering function accordingly.

Categories

Resources