jQuery click works only once - javascript

I want to create a circle everytime I click the button but the once I click it, it creates a circle but when i click it again nothing happen.
$(document).ready(function() {
var circle = $("<div class='circleClass'></div>");
$(".t-testbody").on("click", "#clickMe", function() {
$(".t-testbody").append(circle);
});
});
.t-testbody {
margin-top: 100px;
margin-left: 50px;
}
.circleClass {
width: 50px;
height: 50px;
border-radius: 100%;
background-color: blue;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="t-testbody">
<div class="circleClass"></div>
<button id="clickMe">Button</button>
</div>

Currently you have created the element and appended it to the div. so second append statement has not effect as the element already exist in the div.
Instead of element use HTML string
var circle = "<div class='circleClass'></div>";
$(".t-testbody").on("click", "#clickMe", function () {
$(".t-testbody").append(circle);
});
DEMO
You can use .clone()
var circle = $("<div class='circleClass'></div>");
$(".t-testbody").on("click", "#clickMe", function () {
$(".t-testbody").append(circle.clone());
});
DEMO

You are defining your HTML element only once, so instead of this
$(document).ready(function() {
var circle = $("<div class='circleClass'></div>"); // Move this into event handler callback
$(".t-testbody").on("click", "#clickMe", function() {
$(".t-testbody").append(circle);
});
});
Do this:
$(document).ready(function() {
$(".t-testbody").on("click", "#clickMe", function() {
var circle = $("<div class='circleClass'></div>"); // Move this here
$(".t-testbody").append(circle);
});
});
What's happening is that jQuery creates the HTML element, then on click it moves that element to the div. When you click it again, it moves that same element into where it just was, giving the illusion that it did nothing, but it just moved it into the position it already was.
When you move the variable declaration into the callback, it will generate a new html element every time you click that element, therefore jQuery will be appending a newly defined element to the div.

circle holds the reference of element being appended. So it has no difference after first click.
You can create circle inside the callback function like this :
$(document).ready(function(){
$(".t-testbody").on("click","#clickMe",function(){
var circle = $("<div class='circleClass'></div>");
$(".t-testbody").append(circle);
});
});
.t-testbody {
margin-top: 100px;
margin-left: 50px;
}
.circleClass {
width: 50px;
height: 50px;
border-radius: 100%;
background-color: blue;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="t-testbody">
<div class="circleClass"></div>
<button id="clickMe">Button</button>
</div>
Demo : http://jsfiddle.net/vikashvverma/ou52j2xn/

Related

Removing an appended parent element

I have a list maker that appends items but also appends a trash can item to each of the list items which is made. I have a function on the trash can that should remove the parent element when it is clicked but it doesn't work.
Here is a simple version of what I'm trying to do
JSFiddle
$('button').click(function() {
$('#contain').append('<div class="div"></div>').append('<div class="nested"></div>');
});
$('.nested').click(function() {
$(this).parent().remove();
});
How can I remove the parent element of only the nested div that is clicked?
Use on() because you're calling an event on dynamically appended element.
$('body').on('click', '.nested', function(){
$(this).parent().remove();
});
Also we can use $('#contain') instead of $('body') as well.
$('button').click(function() {
$('#contain').append('<div class="div"></div>').append('<div class="nested"></div>');
});
$('body').on('click', '.nested', function() {
$(this).parent().remove();
});
.div {
width: 100px;
height: 50px;
background: #000;
margin-top: 50px;
}
.nested {
width: 50px;
height: 25px;
background: red;
z-index: 100;
margin-top: -25px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add
</button>
<div id="contain">
</div>
try this:
$('#contain').on('click', '.nested', function(){
});
you have to listen to clicks on the container for appended elements, since they're not in the DOM when the page is loaded
Two issues:
As the others have mentioned, you're binding your .nested click
event before your element is created, meaning it won't have the
event handler attached. As the others mentioned, something like $("#contain").on("click", ".nested", function() {}) will fix the issue
$.append returns the element you are appending to not the element being appended so your .nested is nested under the $("#contain"). This means the $(this).parent() is actually returning the #contain element. A fix for the issue is
$("<div class='nested' />").appendTo($("<div class='div' />").appendTo("#contain"));
Change :
$('.nested').click(function() {
$(this).parent().remove();
});
To:
$(document).on("click",".nested",function(){
$(this).parent().remove();
})

Detect dynamically created elements in JavaScript

I am trying to create a box that expands and collapses using regular JavaScript (No jQuery). The problem I'm running into is detecting how to properly detect dynamically created elements or classes that are added to elements after pageload.
Here's an example JS fiddle page:
http://jsfiddle.net/1a518a4t/3/
As you can see, it works when you collapse and then expand once, but then it won't collapse again.
JS code:
function test() {
var badge = document.getElementById('test');
var close_button = document.querySelector('.test-close');
close_button.addEventListener("click", close_box);
function close_box() {
badge.style.bottom = '-70px';
close_button.classList.add("test-open");
close_button.classList.remove("test-close");
var open_button = document.querySelector('.test-open');
open_button.addEventListener("click", open_box);
}
function open_box() {
badge.style.bottom = '0';
close_button.classList.remove("test-open");
close_button.classList.add("test-close");
}
}
window.onload = test;
I think I really just want to learn how to replicate jQuery's on method in JavaScript. That works for elements that are dynamically created after pageload.
Use a single event listener. And don't modify inline styles, just switch classes:
var badge = document.getElementById('test');
var button = document.querySelector('.button');
button.addEventListener("click", function toggle_box() {
badge.classList.toggle('opened');
badge.classList.toggle('closed');
});
#test {
width: 300px;
height: 100px;
background-color: #ccc;
position: fixed;
bottom: 0;
right: 20px;
transition: all 0.2s;
}
#test.closed {
bottom: -70px;
}
#test > .button {
position: absolute;
top: 10px;
right: 10px;
width: 10px;
height: 10px;
text-indent: -9999px;
cursor: pointer;
background-color: #000;
}
#test.closed > .button {
background-color: #CE312F;
}
<div id="test" class="opened">
<div class="button">Test</div>
</div>
As mentioned in the comments, this is because the created element is added dynamically and as such you need to delegate so event handler can bind it to the created element. To do that you can look at #Ramswaroop solution to do this in native JavaScript. Although I don't think it's even nessisary to change class and re-bind the different functions. Simply use the same <div> and have a toggle function:
var button = document.querySelector('#test div');
button.addEventListener("click", toggle_box);
...
function toggle_box() {
if(badge.style.bottom == '-70px') {
badge.style.bottom = '-0';
toggleClass("test-close", "test-open");
} else {
badge.style.bottom = '-70px';
toggleClass("test-open", "test-close");
}
}
Fiddle Example

Mouseover events of two DIVs, positioned one over the other

I need to trigger the mouseover event of two DIVs positioned one on top of other.
http://jsfiddle.net/hvh8k/
For the DIV in front, if I have given pointer-events:none; I will get the mouseover event of the DIV underneath. But this stops triggering the mouseover event of the DIV in front.
Javascript
$(function () {
var stopAnimation = false;
var loop1 = setInterval(function () {
if(stopAnimation)return;
var L = parseInt($("#back").css("left"), 10) + 10;
if(L > $(window).width())L=-300;
$("#back").css("left", L);
}, 100);
$("#back").mouseover(function () {
stopAnimation = true;
});
$("#back").mouseout(function () {
stopAnimation = false;
});
$("#front").mouseover(function () {
$("#front").animate({width:200}, 100);
});
$("#front").mouseout(function () {
$("#front").animate({width:100}, 100);
});
});
CSS
#back {
width: 300px;
height: 200px;
background-color: #aaa;
position: absolute;
left:0;
cursor: pointer;
}
#front {
width: 100px;
height: 100px;
background-color: #caa;
position: absolute;
left:0;
top:100px;
border-radius:50%;
overflow:hidden;
}
body {
margin:0;
}
HTML
<div id="main">
<div id="back"></div>
<div id="front"></div>
</div>
Don't know if this would be suited for what you are trying to achieve, but what about toggling the z-index as you click the divs?
First div.front will show. When div.front is clicked, it calls your function AND move div.front to the back, and div.back to the front, which would allow you to click and trigger the div.back function and toggle the divs again.
So to be clear... front visible > click > back visible > click > front visible etc.

jQuery slideUp bugs after page is scrolled

I'm experiencing some problems with jQuery's slideUp and slideDown functions. If you go to this site
www.confide.re/confide
and click on one of the boxes, it normally works fine, but after you scroll the page and it loads some more boxes, then the slide function bugs and does it twice for no reason, if you get what I mean.
Is this something I've done wrong somewhere or is this a known bug?
Thanks
Here is the code:
var state = 'down';
$('.overlay').click(function() {
if(state == 'down') {
$(this).next().slideDown(155);
state = 'up';
} else {
$(this).next().slideUp(150);
state = 'down';
}
.overlay is a transparent div on top of each of the boxes.
Define your click event outside your ajax success callback like this (Use a better selector that body, it is just for the example)
$("body").on("click", ".overlay", function(e){
$(this).next().slideToggle(150);
$(this).css('background-color', 'rgba(0,0,0,0)');
});
you should do something like this: http://jsfiddle.net/chanckjh/Jak6Q/
html:
<div class="something">
<div class="bar">
</div>
</div>​
jquery:
$(function() {
$('.something').click(function() {
$('.bar').slideToggle();
});
});​
css:
.something{
width: 500px;
height: 500px;
border: 1px solid red;
}
.bar{
display: none;
width: 500px;
height: 50px;
background: blue;
}​
or like this for the child: http://jsfiddle.net/chanckjh/Jak6Q/1/
$(function() {
$('.something').click(function() {
$(this).find('.bar').slideToggle();
});
});​
You can not share a single variable state amongst many elements which need to record their specific status. Instead, you have to keep state for each of the elements.

Moving elements between 2 div's with jQuery

I am trying to move divs between two containers (#one and #two). I can't seem to figure out how to select a div which is inside another div.
I found a similar topic about targeting class inside a div. It gave me idea of using parent.
jQuery has a large list of selectors, I assume I could use one of them. But I intuitively think I could use something like #one.draggable or some other kind of specifying path.
Example on JSFiddle
CSS:
div
{
display:inline;
background-color:#eee;
}
.draggable
{
width: 50px;
height: 50px;
background-color: lime;
z-index: 2;
display: block;
float: left;
background-color: #333333;
}
#one
{
width: 200px;
height: 200px;
background-color: #555555;
z-index: 1;
float: left;
}
#two
{
width: 200px;
height: 200px;
background-color: #777777;
z-index: 1;
float: left;
}
jQuery:
$(document).ready(function() {
$(".draggable",$(this).parent("one")).click(function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$(".draggable",$(this).parent("two")).click(function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});
HTML:
<div id="one">
<div class="draggable">1</div>
<div class="draggable">2</div>
<div class="draggable">3</div>
</div>
<div id="two">
<div class="draggable">4</div>
<div class="draggable">5</div>
<div class="draggable">6</div>
</div>
I'll try to stick to what seems to be the core of your question: use $('#one .draggable') (the space is important!) to select all divs with class 'draggable' inside the div with id 'one'.
So your full jQuery code should be:
$(document).ready(function() {
$('#one .draggable').click(function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$('#two .draggable').click(function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});
UPDATE
As you noticed, with the code above it's not possible to move the same div again after the first move. The solution is as follows:
$(document).ready(function() {
$('#one .draggable').live('click', function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$('#two .draggable').live('click', function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});

Categories

Resources