Show last fadeIn div on first position - javascript

I have 10 divs which were displayed in a random time.
How can I set the last shown div on top (rank first position) each time and not in the html order of the divs?
Here is my code:
var myVar;
function showDiv(){
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval(){
setTimeout(showDiv, 500+ Math.random() * 4000);
}
$(document).ready(function(){
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0,0,0,0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;/* hide initially so that fadIn() fadeOut() will work
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
Here is my fiddle: https://jsfiddle.net/gkq21ppt/3/
EDIT: Idea for a solution
A solution could be, to wrap the divs and set them column-reverse. And then add a JS-code which sets a sequential number as flex order number to every new faded in div.
But I have no idea how to do this, with my low JS skills.
So the loop could look like:
create number starting by 1 as variable
create class width name e.g. "order-[number]"
in ".order-[number]" class set css property "order" to [number]
add this class to the loop before it is faded in
remove this class after it is faded out
Or?

You can try using .prependTo()
What this will do (I think) is remove the active notification and add it back to the container, in the first position. Because of this behaviour, flexbox shouldn't be necessary.
Note this changes the HTML structure.
updated fiddle
var myVar;
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval() {
setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;
/* hide initially so that fadIn() fadeOut() will work */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
</div>

Related

How to change the style of a div and reset it after 1000ms?

I have multiple (only 2 in this example) divs overlapping with each other...
What I'd like to do is to add buttons that represents each div, which when clicked, should increase their respective div's z-index for 1000ms only, in order to stay on top of all the other overlapping divs. This is the only purpose of the increase in z-index.
I was able to do some part of this, however, on second round of clicking, the secondary divs keep hiding behind the originally-on-top div.
Please check and run the snippet below:
function increaseDivOne() {
const box = document.getElementById('Div1');
box.style.zIndex = '999';
setTimeout(function () {
box.style.zIndex = '1';
}, 1000);
}
function increaseDivTwo() {
const box = document.getElementById('Div2');
box.style.zIndex = '999';
setTimeout(function () {
box.style.zIndex = '1';
}, 1000);
}
#Div1 {
position: absolute;
width: 300px;
height: 150px;
background-color: lightblue;
border: 1px solid black;
}
#Div2 {
position: relative;
top: 130px;
left: 30px;
width: 300px;
height: 150px;
background-color: coral;
border: 1px solid black;
}
<button onclick="increaseDivTwo()">Increase Div 2</button>
<br><br>
<button onclick="increaseDivOne()">Increase Div 1</button>
<ul>Try this:</ul>
<li>Click "Increase Div 2"</li>
<li>Click "Increase Div 1"</li>
<li>Click "Increase Div 2" again and notice it will show up but will hide behind Div1 after 1s</li>
<p>My goal is to raise the z-index of a div for 1s, just enough to be on top of the other div and vice versa, but it should stay on top after the 1s set timeout. <br> Please note there's more Div in my actual project that will utilize this function.</p>
<div id="Div2">
<h1>Div 2</h1>
</div>
<div id="Div1">
<h1>Div 1</h1>
</div>
Thank you in advance for any help.
From the discussion in comments, I think it would be enough if you just reset the z-index for the currently on-top one, when a new one needs to be moved to the front - without any timers.
You could loop over all relevant div elements - or simply remember the previous one in a variable, and then reset z-index specifically for only that.
And then it would also be a bit nicer, if we did not manipulate inline styles for this, but simply set a class to apply the necessary z-index to the currently "active" element.
var previous = null;
function increaseDiv(num) {
if(previous) {
previous.classList.remove('active');
}
var div = document.getElementById('Div'+num);
div.classList.add('active');
previous = div;
}
#Div1 {
position: absolute;
width: 300px;
height: 150px;
background-color: lightblue;
border: 1px solid black;
}
#Div2 {
position: relative;
top: 130px;
left: 30px;
width: 300px;
height: 150px;
background-color: coral;
border: 1px solid black;
}
div.active {
z-index: 999;
}
<button onclick="increaseDiv('2')">Increase Div 2</button>
<br><br>
<button onclick="increaseDiv('1')">Increase Div 1</button>
<div id="Div2">
<h1>Div 2</h1>
</div>
<div id="Div1">
<h1>Div 1</h1>
</div>
if the divs got the same index, then the childnode order takes relay on priority of display, that's the problem here, to keep priority on the last div selected, you should then rewrite your function as the following :
function increaseDivOne() {
const box = document.getElementById('Div1');
box.style.zIndex = '999';
setTimeout(function () {
box.style.zIndex = '1';
var elms=document.querySelectorAll('div[id^="Div"]:not(#Div1)');
for (var p in elms) {
elms[p].style.zIndex=-1;
}
}, 1000);
}

Hover on two elements using jQuery

I have two <div> elements attached to each other, I mean there is no space between them.
<div id="box1">1</div>
<div id="box2">2</div>
And I have this jQuery code:
$('#box1 , #box2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
My problem is when I move the mouse between box1 and box2, I still get on console log "Not".
I want those divs to be considered as one element so when I move the mouse between them I don't get on console log "Not".
Thanks in advance!
I want those divs to be considered as one element
Well, quite simply, they aren't. And they can't be. That's not how HTML and CSS works.
The hover event is triggered one for each individual element bound to the event handler. And every time you leave one of those elements it will print the "not" output as per your instructions.
There is no "fix" for this in the exact way you described, but there are alternative approaches. An obvious solution is to wrap them both in an outer div and bind the hover event to that instead. Then the whole area will be considered as one element (because it literally is). Demo:
$('#boxcontainer').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
#boxcontainer {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxcontainer">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
friend check the code below. I think it will work for you. As you have dai you have an absolute position div you must need a parent div and the parent div position must be relative. For doing that you have to add just a simple CSS code position: relative;. You also need to do some changes to your jquery code. You can just hover on the parent div and it will do your work. Hope this code will help you.
//Box 1 Demo
$('#boxParrent1').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
//Box 2 Demo
$('#boxParrent2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
/*Main Code that are needed*/
#boxParrent1, #boxParrent2 {
position: relative;
}
/*Codes Just used to give you a demo*/
#boxParrent1, #boxParrent2{
display: flex;
margin-bottom: 50px;
border: 1px solid #000;
}
#boxParrent1{
width: 200px;
}
#boxParrent2{
width: 210px;
}
#box1, #box2, #box3, #box4{
background: tomato;
width: 100px;
height: 100px;
display: grid;
justify-content: center;
align-items: center;
font-family: Arial;
font-size: 50px;
color: #fff;
cursor: pointer;
}
#box2, #box4{
position:absolute;
top: 0;
left:100px;
background: #02dce6;
}
#box4{
left:110px;
background: #02dce6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxParrent1">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
<div id="boxParrent2">
<div id="box3">3</div>
<div id="box4">4</div>
</div>
Try to place your 2 div's in one super div
<div id="super">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
$('#super').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});

If hasClass help and subtracting from variables

I am trying to make it so when the '.main' is clicked, it will toggle its class to become a '.second', with this new class it will become red but the element will have already been classed as '.main' already, thus, I can still refer to it as '.main'. After that I want it to add to the 'count' variable and, if clicked again, revert back to the appearance of the '.main' class, then subtracting from the 'count' variable!
html
<div class="container">
<div id="box" class="main"></div>
<div id="box" class="main"></div>
<div id="box" class="main"></div>
<div id="box" class="main"></div>
</div>
relevent css
.main {
background: #888888;
}
.second {
background: red;
}
#box {
width: 10px;
height: 10px;
border-radius: 10px;
margin: 1% 1%;
line-height: 100px;
text-align: center;
}
And, jQuery
$(document).ready(function() {
var count = 0;
$('.main').click(function() {
$(this).toggleClass('second')
$(this).toggleClass('main')
if ($(this).hasClass('main')) {
count++;
} else if ($(this).hasClass('second')) {
count--;
}
if (count === 4) {
alert('Success')
}
});
});
So I need help because the jQuery will keep adding to the 'count' variable even if 'this' hasClass '.second'!
IF YOU THINK YOU HAVE AN ANSWER CHECK IT IN JSFIDDLE AND CLICK THE ONE BOX 4 TIMES, IF YOU GET A PROMPT THEN THE 'COUNT--;' ISN'T SUBTRACTING STILL
You may need to change these.
Remove the count variable and instead use jQuery's length.
Do not use the same value for ID.
$(document).ready(function() {
$('.main').click(function() {
$(this).toggleClass('second').toggleClass('main')
if ($('.main').length == 4)
alert('Success')
});
});
.main {
background: blue;
}
.second {
background: red;
}
#box1, #box2, #box3, #box4 {
width: 10px;
height: 10px;
border-radius: 10px;
margin: 1% 1%;
line-height: 100px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div id="box1" class="main"></div>
<div id="box2" class="main"></div>
<div id="box3" class="main"></div>
<div id="box4" class="main"></div>
</div>
You need to remove $(this).toggleClass('main') from within $('.main').click(function() { updating the code to
$('.main').click(function() {
$(this).toggleClass('second')
if ($(this).hasClass('second')) {
count++;
} else if ($(this).hasClass('main')) {
count--;
}
if (count === 4) {
alert('Success')
}
});
when you toggle the .main class it is removed and it will not fall within the click call
And you can't have multiple items with the same ID within your HTML, you can assign class if it occurs more than once. See the fiddle linked below for an example of how you can have it
jsfiddle example: http://jsfiddle.net/ks14dnL1/4/

JavaScript Wrap Around Carousel

I am looking for some information from some front end experts on how to go about creating a custom wrap around js carousel gallery. The idea is simple really I have a carousel of images, text, or whatever and when I get to the end I want it to wrap around. I don't want the content to simply fadeIn and out to the next piece of content. This is a gallery of div's currently but suppose it's images or whatever have you.
HTML
<div id="outside-container">
<div id="inside-container" class="cf">
<div class="items" id="item1"></div>
<div class="items" id="item2"></div>
<div class="items" id="item3"></div>
<div class="items" id="item4"></div>
</div>
</div>
<div id="directions">
<h4 id="left-button">Left</h4>
<h4 id="right-button">Right</h4>
</div>
CSS
#outside-container{
display: block;
width: 400px;
height: 125px;
overflow: hidden;
border: 1px solid #000;
margin: 0px auto;
}
#inside-container{
display: block;
width: 800px;
overflow: hidden;
height: 100%;
}
.items{
float: left;
margin: 0px;
width: 200px;
height: 100%;
}
#item1{ background: green; }
#item2{ background: red; }
#item3{ background: blue; }
#item4{ background: yellow; }
#directions{
display: block;
width: 400px;
margin: 0px auto;
text-align: center;
}
#left-button, #right-button{
display: inline-block;
cursor: pointer;
margin: 10px;
}
JS
var move = 0;
$("#left-button").click(function(){
move += 200;
$("#inside-container").animate({
marginLeft: move+"px"
}, 500);
});
$("#right-button").click(function(){
move -= 200;
$("#inside-container").animate({
marginLeft: move+"px"
}, 500);
});
Here is the codepen. So to sum all this up. I am asking for a way to create an infite loop for a gallery. I have always programmed these sorts of things to come to an end and then the user has to go back the other way. If this sounds confusing follow check out the codepen. Thanks in advance.
Here you go
http://codepen.io/nickavi/pen/cpFCE
But for the love of god, please don't use jQuery animate... at least add velocity.js to it, or the GSAP plugin, you don't even have to alter your JS you just add it in and it replaces the animate function with a more efficient one.
Cheers JBSTEW
First set move to the default slider and margin reset amount:
var move = 200;
Then, set the container margin to slide left by the move amount:
var margin_reset = (move * -1) + 'px'
$("#inside-container").css('margin-left', margin_reset);
Then, adjust the animation margin slide using move variable again, and execute a function when the animation is complete that moves the last/first item to the beginning/end of the container using prepend/append.
$("#left-button").click(function(){
$("#inside-container").animate({
marginLeft: 0
}, 500, function() {
$(this).prepend( $(this).find('.items:last') )
.css('margin-left', margin_reset);
});
});
$("#right-button").click(function(){
$("#inside-container").animate({
marginLeft: (move * -2) +"px"
}, 500, function() {
$(this).append( $(this).find('.items:first') )
.css('margin-left', margin_reset);
});
});
To avoid an initial draw jump, you could change the default css #inside-container as:
#inside-container{
...
margin-left: -200px;
}
see: Codepen

Display value in jQueryUI ProgressBar

I've set up a simple jQuery UI ProgressBar:
<script type="text/javascript">
$(function() {
$("#progressbar").progressbar({
value: 35
});
});
</script>
<div id="progressbar"> </div>
Among other things, I'd like to display some text in the progress-bar (for starters, I'd just use the "value").
I can't seem to get this to work.
Bonus Question: How do I format the displayed text (e.g. color, alignment)?
Instead of introducing another element (span) and a new style, leverage what is already there like this:
var myPer = 35;
$("#progressbar")
.progressbar({ value: myPer })
.children('.ui-progressbar-value')
.html(myPer.toPrecision(3) + '%')
.css("display", "block");
The css("display", "block") is to handle the case where the value is 0 (jQuery UI sets a display: none on the element when the value is 0).
If you look at the source of The demo, you'll notice that a <div class="ui-progressbar-value"> is added. You can simply override this class in your own CSS, like:
.ui-progressbar-value {
font-size: 13px;
font-weight: normal;
line-height: 18px;
padding-left: 10px;
}
The way I did it was:
<div class="progressbar"><span style="position:absolute; margin-left:10px; margin-top:2px>45% or whatever text you want to put in here</span></div>
You can adjust the margin-top and margin-left so that the text is in the center of the progress bar.
Then you apply the progressbar plugin for the elements which have class progressbar in the javascript section of the page
Hope this help
After fiddling around with some solutions, based on the answers here, I've ended up with this one:
Html:
<div id="progress"><span class="caption">Loading...please wait</span></div>
JS:
$("#progress").children('span.caption').html(percentage + '%');
(To be called inside the function that updates the progressbar value)
CSS:
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
Advantages:
Caption is centered with no harcoded positioning (necessary if caption width changes dinamically)
No JS strange manipulation
Simple and minimal CSS
This solution allows for a flexible width based on the text as well as centering the text, styling the text, etc. Works in Chrome, FF, IE8, and IE8 in compatibility mode. Didn't test IE6.
Html:
<div class="progress"><span>70%</span></div>
Script:
$(".progress").each(function() {
$(this).progressbar({
value: 70
}).children("span").appendTo(this);
});
CSS:
.progress.ui-progressbar {position:relative;height:2em;}
.progress span {position:static;margin-top:-2em;text-align:center;display:block;line-height:2em;padding-left:10px;padding-right:10px;}
.progress[aria-valuenow="0"] span {margin-top:0px;}​
Working sample: http://jsfiddle.net/hasYK/
I used this:
<div id="progressbar" style="margin: 0px 0px 16px 0px; "><span style="position: absolute;text-align: center;width: 269px;margin: 7px 0 0 0; ">My %</span></div>
<style>
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
</style>
</head>
<body>
test
<div id="progressbar"></div>
<br>
test2
<div id="progressbar2"></div>
<script>
$("#progressbar").progressbar({
max : 1024,
value : 10
});
$("#progressbar2").progressbar({
value : 50
});
$(document).ready(function() {
$("#progressbar ").children('div.ui-progressbar-value').html('10');
$("#progressbar2 ").children('div.ui-progressbar-value').html('50%');
});
</script>
</body>

Categories

Resources