Add div below another div - javascript

I have a requirement to add 5 divs one by one on each click of a div button. ( the new div should be added below the existing div)
I done the code, but the news ones are getting attached on the top of existing div. please help to correct this.
I have another button which removes the added divs one by one(new ones to be remove first)
here is my code.
<div class="clearFix"></div>
<div id="containershowmore" >
<div id="dragbtnmore" style="cursor: default;">Show more buttons</div>
<div id="dragbtnless" style="cursor: default;">Show Fewer buttons</div>
</div>
<div class="toAdd" style="display:none;" >
<div id="dragdashboardmain" style="cursor: pointer;">dash</div></div>
<div class="toAdd" style="display:none;" >
<div id="dragrcalendar" style="cursor: pointer;">Calendar</div></div>
<div class="toAdd" style="display:none;">
<div id="dragresourcelist" style="cursor: pointer;">Rlist</div></div>
<div class="toAdd" style="display:none;">
<div id="dragdailynotes" style="cursor: pointer;">D Notes</div></div>
<div class="toAdd" style="display:none;">
<div id="dragweeklynotes" style="cursor: pointer;">W Notes</div></div>
script:
$("#dragbtnmore").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'none') {
$(this).css('display', 'block');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'none') {
i++;
}
});
if (i == 5)
$('#dragbtnmore').click(function () { return false; });
});
$("#dragbtnless").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'block') {
$(this).css('display', 'none');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'block') {
i++;
}
});
if (i == 5)
$('#dragbtnless').click(function () { return false; });
$('#dragbtnless').click(function () { return true; });
});
$("#containershowmore").mouseleave(function () {
$(this).hide();
});
function showmore() {
document.getElementById('containershowmore').style.display = "block";
}
style:
#containershowmore
{
margin-top: -75px;position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float: right;
padding-left: 5px;
}
.toAdd
{
background-color: blue;
margin-top: -55px;
position: relative;
margin-bottom: 14px;
}
*I referred this Fiddle *
**Solution:
Thankyou Shivam Chopra for helping me . Thanks a TON!! :)
for others, HEre is the solution**
jsfiddle.net/coolshivster/YvE5F/12

Remove margin top from both the div.
#containershowmore
{
position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float:right;
padding-left: 5px;
}
#dragbtnmore{
margin-bottom:10px;
border:1px solid black;
}
.toAdd
{
height:20px;
width:70px;
background-color: blue;
position: relative;
margin-bottom: 14px;
}
Then, it will work accordingly.
Here, the code : http://jsfiddle.net/coolshivster/YvE5F/
I have rewritten your code according to your requirement.
Some explanation about the code
I have create a parent div element with id="Add-element" that covers every element which contains class .toAdd .
Then I created data attribute for every div containing class .toAdd .
Now, I display the element one by one. But after first element. Every other element will prepend on the parent div i.e., #Add-element class.
Now, the code which I have rewritten.
jsfiddle link : http://jsfiddle.net/YvE5F/10/

Related

jQuery .not() and :not with new classes? [duplicate]

This question already has answers here:
jQuery click event not working after adding class
(7 answers)
Closed 2 years ago.
I have some card to flip and check if one is equal to another (memory game).
If I flip the card, I don't want that is possible to click and run function if I click on the same card (that is .flipped) or on another that is flipped. But jQuery .not() and :not not working. Maybe I must read another time the DOM after .toggleClass?
$(".card:not('.flipped')").on("click", function () {
$(this).toggleClass("flipped");
if (first) {
firstCard = $(this).attr("game");
first = false;
} else {
secondCard = $(this).attr("game");
first = true;
checkGame();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The code is binding the events when it is called. So whatver the classes are at that moment in time, is what it finds and binds the event.
So you need to check for the class inside of the method and exit it
$(".card").on("click", function() {
var card = $(this);
if (card.hasClass("flipped")) return;
console.log(this);
card.addClass("flipped");
});
.wrapper {
display: flex;
}
.wrapper > .card {
flex: 1;
text-align: center;
line-height: 50px;
font-size: 30px;
}
.card.flipped {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
</div>
Other option is using event delegation where you bind the event to the parent and element and have jQuery do the checking if the class is added yet.
$(".wrapper").on("click", ".card:not('.flipped')", function() {
console.log(this);
var card = $(this);
card.addClass("flipped");
});
.wrapper {
display: flex;
}
.wrapper > .card {
flex: 1;
text-align: center;
line-height: 50px;
font-size: 30px;
}
.card.flipped {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
</div>
Apply the click event to all cards.
On click, check if the card is flipped. If it is, do nothing.
Cache your jQuery objects.
$(".card").on("click", function() {
const $card = $(this);
if ($card.hasClass("flipped")) return;
$card.toggleClass("flipped");
// .........
});
you have to check it inside your event 'click'. if the card has class 'flipped' break it
$(".card").on("click", function () {
if($(this).hasClass('.flipped')) return;
$(this).toggleClass("flipped");
if (first) {
firstCard = $(this).attr("game");
first = false;
} else {
secondCard = $(this).attr("game");
first = true;
checkGame();
}
});

jQuery - element crossing another element

I have a fixed div on the page which contains a logo and as the user scrolls and this logo passes over other divs I wnat to the change the colour of the logo.
I have this working over a single div but need to it work across multiple so any help appreciated.
The WIP site can be seen here... dd.mintfresh.co.uk - if you scroll down you'll (hopefully) see the logo change from black to white as it crosses an illustrated egg. I need the same to happen when it crosses other divs further down the page.
The script so far...
jQuery(window).scroll(function(){
var fixed = jQuery("logo");
var fixed_position = jQuery("#logo").offset().top;
var fixed_height = jQuery("#logo").height();
var toCross_position = jQuery("#egg").offset().top;
var toCross_height = jQuery("#egg").height();
if (fixed_position + fixed_height < toCross_position) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else if (fixed_position > toCross_position + toCross_height) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else {
jQuery("#logo img").css({filter : "invert(0%)"});
}
}
);
Any help appreciated. Thanks!
you need to fire a div scroll event. you can assign
$("div1").scroll(function(){
//change the color of the div1
}
});
$("div2").scroll(function(){
//change the color of the div2
}
});
or you can assign a class to divs which you want to change the color
$(".div").scroll(function(){
//change the color of the div which you are scrolling now
}
});
You can use like this :-
$(window).scroll(function() {
var that = $(this);
$('.section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('active')) {
$('.logo').addClass('invert');
} else {
$('.logo').removeClass('invert');
}
}
});
});
body {
padding: 0;
margin: 0;
}
div {
background: #f00;
height: 400px;
}
.logo {
position: fixed;
top: 0;
left: 0;
width: 100px;
}
.logo.invert {
filter: invert(100%);
}
div:nth-child(even) {
background: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://dd.mintfresh.co.uk/wp-content/uploads/2018/06/DD_logo.svg" class="logo" />
<div id="page1" class="section"></div>
<div id="page2" class="section active"></div>
<div id="page3" class="section"></div>
<div id="page4" class="section active"></div>
<div id="page5" class="section"></div>
As your site code you can do like this :
$(window).scroll(function() {
var that = $(this);
$('#content > section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('black')) {
$('#logo img').css({filter: 'invert(0%)'});
} else {
$('#logo img').css({filter: 'invert(100%)'});
}
}
});
});

Remove (and Add) Classes to HTML Element with jQuery, While Updating the DOM tree

I'm trying to change a div's attribute class. I have three defined classes and want to cycle through the classes when a user initiates a click event. The first click event works as expected, but the second doesn't show any results.
I've went through a few iterations of trying to get this to work, but have not had any success. I think what's going on is that the DOM tree isn't being updated with the click event, so when the second click event is fired it sees the card-green class, adds the card-yellow class and then exits the branching logic.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[0]);
}
})
});
Use a switch and toggleClass(). Details are commented in Snippet. No need for an array if you are using a limited number of options. When using $(this) you don't need to keep track of what you clicked (much like event.target except $(this) isn't concerned about events as it is concerned with owner of function.)
SNIPPET
$(document).ready(function() {
$(document).on('click', 'div', function(event) {
/* Determine $(this) class
|| Pass class through the switch
*/
var color = $(this).attr('class');
/* Each part of the switch is a if/else
|| conditional. If the condition isn't
|| met, then it will kick you
|| down to the next conditional and
|| so on, until you reach default or
|| meet a condition in which case the
|| break will kick you out of switch.
|| Each condition has a toggleClass()
|| method to switch colors according
|| to the present class of div
*/
switch (color) {
case 'green':
$(this).toggleClass('green yellow');
break;
case 'yellow':
$(this).toggleClass('yellow red');
break;
case 'red':
$(this).toggleClass('red green');
break;
default:
break;
}
});
});
div {
height: 30px;
width: 50px;
border: 1px solid black;
cursor: pointer;
}
.green {
background: green
}
.red {
background: red;
}
.yellow {
background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
This changes the color in order of the cards array when elements within the document body are clicked:
(Very similar to #gyre's answer, only includes the event.target within the code logic, rather than just the body).
var cards = ['card-green', 'card-yellow', 'card-red'];
$('body').on('click', function() {
var elem = event.target,
curClass = $(elem).attr('class'),
i = cards.indexOf($(elem).attr('class'));
$(elem)
.removeClass(curClass)
.addClass(cards[i = (i + 1) % cards.length]);
});
div {
height: 100px;
width: 100px;
display: inline-block;
}
.card-green {
background-color: green;
}
.card-yellow {
background-color: yellow;
}
.card-red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="card-green"></div>
<div id="bar" class="card-yellow"></div>
<div id="baz" class="card-red"></div>
Use an additional index variable to keep track of the position in the array:
Demo Snippet:
$(document).ready(function() {
var cardColors = ['card-green', 'card-yellow', 'card-red']
var i = 0
$('body').on('click', function() {
$(this)
.removeClass(cardColors[i])
.addClass(cardColors[i = (i + 1) % cardColors.length])
})
})
body {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
}
.card-green { background-color: green; }
.card-yellow { background-color: yellow; }
.card-red { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The same code is workable just remove nodeName from removeClass(event.target.nodeName.className) instead of this use removeClass(event.target.className).
Try this, Its working for me.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
alert(event.target.className)
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[0]);
}
})
});

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

$('#div').bind('scroll' function({})) not working

I have added 2 codes here the window.scroll works on my example but not the second one binding the div to the scroll.
Any one knows what am I doing wrong!?
Just so you know I'm working in MeteorJS <- I dont think that this is the problem bc. the window scrolling works.
This 2 codes are in the same js file.
$(window).scroll(function() {
lastSession = Session.get('c_info')[Session.get('c_info').current]
if(lastSession.list == 0 && $(window).height() + $(window).scrollTop() >= $(document).height()){
lastItem = $( ".list-item div:last" ).html();
if (lastSession.page == 1){
currentSession().more();
lastItem2 = $( ".list-item div:last" ).html();
} else if( lastItem2 != lastItem) {
currentSession().more();
lastItem2 = $( ".list-item div:last" ).html()
}
}
});
$('#playlist').bind('scroll',function() {
console.log("div is scrolling");
});
I tried this too:
$('#playlist').scroll(function() {
console.log("div is scrolling");
});
MeteorJS Template:
<template name="playList">
<div id="playlist" class="playlist show-for-large-up">
{{#each list}}
<a href="/video/{{_id}}" class="large-12 columns" id="pl{{v_id}}">
<div>
<div class="large-7 columns plRight">
<span>{{vTitle}}</span>
</div>
</div>
</a>
{{/each}}
</div>
</template>
Also Tried:
$('#playlist').on('scroll',function() {console.log('test')});// not working
Tried to Change the id name and putting on the document ready:
$( document ).ready(function (){
$('#pl_list').bind('scroll',function() {
console.log("div is scrolling");
});
})//failed
The div has a scrollbar and the list is long and i have a css like this:
.playlist {
padding: 0;
overflow-y: scroll;
height: 458px;
}
Also tried:
Template.playList.rendered = function () {
console.log("playlist rendered");// i can see this on logs this tells that template is in doom
Meteor.setTimeout(function(){
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
}, 2000);// with settimeout i have giveng it 2 more seconds
}
Try this out -
$(document).ready(function(){
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
});
Use
$('#playlist').scroll(function() {
console.log("div is scrolling");
});
instead (like you did for window).
Thats the purpose of scroll(). See jquery documentation.
Scrolling event is fired on the element, if it has scrolled. So if you only scrolling the "body" element of the DOM it will not be triggered for #playlist.
So you have put a scrollbar to the container element of #playlist. Shot answer, cut the height and add a scrollbar, then the event will fire on it.
I did a Jsfiddle http://jsfiddle.net/34j0qnpg/4/
html
<div id="playlist-wrapper">
<div id="playlist" class="playlist show-for-large-up">
<a href="/video/1" class="large-12 columns" id="pl1">
<div>
<div class="large-7 columns plRight">
<span>Titel</span>
</div>
</div>
</a>
css part
body, html {
padding: 0;
margin: 0;
background-color: lightgrey;
color: #fff;
font-family: Arial;
height: 5000px;
overflow-y:scroll;
}
#stats {
position: relative;
}
#playlist-wrapper {
border: 1px solid #000;
padding: 10px;
height: 300px;
overflow-y: scroll;
}
#playlist {
height: 1000px;
background-color: darkgrey;
}
var $stats = $('#stats');
$('#playlist-wrapper').on('scroll', function() {
$stats.html('playlist scrolling');
console.log('playlist scrolling');
});
$(window).on('scroll', function() {
$stats.html('window scrolling');
console.log('window scrolling');
});
Solved with this code:
Tried it earlyer no results, after meteorjs project reset it just automagicly workded:
Template.playList.rendered = function () {
console.log("playlist rendered");
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
}
I answered my question just if anybody is searching for the same answer.
Thanks to anybody who tried to help me.
I LOVE THIS COMMUNITY.

Categories

Resources