Remove div element on click jQuery not working - javascript

What I need :
I am trying to create tags on the click of a button. I was successful with my attempt to create divs on the click.
Problems :
As in all the websites one has seen, like in stack-overflow or when you write email addresses , as you finish writing the text a "tag" is formed with a "remove" button when you hover.
Now I want something like this, but I am confused in how to show that cross on the divs.
Also my problem is when I use elements, I am also giving some background color but that is static. And if the text grows then there is no background color on the part of the text.
How should I go about this problem ?
This is what I have tried so far : http://jsfiddle.net/abhighosh18/wk9uxfz5/1/
JS :
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
width : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
float : 'left'
}).appendTo("#content");
});
$('#newCo').on('click',function(){
$(this).remove();
});

Some illumination --
$('#newCo').on('click',function(){
$(this).remove();
});
The above won't work because the #newCo element does not exist at the time that line executes.
$(document).on('click','#newCo',function(){ $(this).remove(); });
This refactored line of code listens to the document and WILL work on elements that don't exist at the time the DOM is first loaded. However, ID is not what you want to use here... because IDs need to be unique and there would quickly be several div withs the same ID if you click the .btnAdd element.
There are many ways to accomplish what you want, I just wanted to illustrate why your approach is failing.
THE FIX: you could chain .addClass("removable-tag") within your div-creating click function (before .appendTo()), and listen to $(document).on('click','.removable-tag',function(){...});, and THAT would function as intended.

You can use display: inline-block css property and min-width instead of width:
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
minWidth : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
display: 'inline-block'
}).appendTo("#content");
});
http://jsfiddle.net/Lathtqd8/

NOTE: What follow is an answer to this part of question ( before update ) :
Now what I need is the CSS for the divs to be placed side-by-side. I
have seen the code for doing so, but I need to know how to write the
code for dynamically generated divs.
Another thing i tried was creating buttons instead of divs. That
placed my buttons side by side without any extra effort from CSS.
add this to your css :
#newCo {
float: left;
}
and remove the forcing width : '30px', from your JS code otherwise it will get broken on large content.
http://jsfiddle.net/tunecino/wk9uxfz5/5/

Add some class not id when you want to add multiple elements.
snippet added
--joy
//javascript
$('.btnAdd').on('click', function () {
$('<div/>', {
class: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val(),
'data-idn':'some_unique_number'
}).append('<a>x</a>')
.appendTo("#content")
.find('a').click(function(){
var idn = $(this).parent().data('idn');
$(this).parent().remove();
//removeCallback(idn); //call anything with idn if required
});
});
/*CSS*/
.newCo{float:left;min-width:30px;background:lightblue;font-weight:700;padding:2px;margin:5px;}
.newCo > a {cursor:pointer;margin:0 0 0 3px;border-radius:50%;color:red;padding:0;text-shadow:0px 0px 1px #fff;font-weight:200;font-size:16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Product Name:<input id="prodName" type="text">
<button class="btnAdd" value="Click Me!">Add Product</button>
<br/><br/><br/><div id="content" height="100px" width="100px" style="color:blue"></div>

try this:
$("#mydiv").off('click');

Related

How to reverse hover state with jQuery?

My assignment requires that I use jquery only. Doesn't seem practical but I'm limited. I was able to figure out how to do a hover state but when the styles get applied, it stays. So check this out..
$(".cta-button").css({
background: "#476887",
"text-align": "center",
width: "173px",
height: "40px",
margin: "62px auto 33px",
cursor: "pointer"
});
$(".cta-button").hover(function() {
$(this).css("background-color", "#509de5");
});
Of course when I'm no longer hovering, I want it to revert back to it's original background color. How do I go about doing this? Thanks!!
You can easily achieve that by using the hover method of jQuery
As stated in the docs, this method can accept one to two arguments, the first one is called the handlerIn which can be translated as the hover state, mouse enter, etc and the handlerOut which corressponds to the 'mouse leave'
So to achieve what you want you can try something like this
$('DOM_NODE').hover(mouseEnter, mouseLeave);
function mouseEnter() {
// do something when the mouse enters the dom node
};
function mouseLeave() {
// do something when the mouse leaves the dom node
};
You can add mouseover eventa fiddle
$(".cta-button").css({
background: "#476887",
"text-align": "center",
width: "173px",
height: "40px",
margin: "62px auto 33px",
cursor: "pointer"
});
$(".cta-button").hover(function() {
$(this).css("background-color", "#509de5");
}).mouseover(function() {
$(this).css("background-color", "#476887");
});

How to style the container of a jQuery Select2 combo box?

Is it possible to style the combo box container using the Select2 jQuery plugin? I can successfully style the dropdown menu where autocomplete selections appear, but not the container where text is entered. Here's what I'm doing:
$(document).ready(function() {
$("#combo").select2({
data:[{id:0,text:'One'},{id:1,text:'Two'}],
multiple: true,
createSearchChoice: function (term) {
return { id: term, text: term };
},
containerCss: 'container',
dropdownCssClass: 'dropdown',
containerCss: {
background: 'green'
}
});
});
<input type="hidden" id="combo" style="width:350px" />
#combo {
background: green;
}
.container {
background: green;
}
.dropdown {
background: red;
}
The container should be green, but it's not. Here's a fiddle.
Edit:
I noticed on the documentation page for the site (which is quite comprehensive) that every example of the kind I'm trying to do (hidden input field with dynamically loaded options) has the same standard style, like in my example fiddle. The version that originates from a select element, however, has rounded corners etc. If this means you can't style the container when using a hidden input, it's seems like an odd limitation.
Edit2:
#emmanuel has already provided a solution, but since I was actually after the border-radius, there was a bit more to do to get it working properly. After setting the radius on all corners, opening the dropdown results in rounded corners visible between the top of the dropdown and the bottom of the container, which is a bit ugly. You can do something like this to fix it:
$('ul.select2-choices').on("select2-open", function() {
$('ul.select2-choices').css({
'border-bottom-left-radius': '0px',
'border-bottom-right-radius': '0px',
});
});
$('ul.select2-choices').on("select2-close", function() {
$('ul.select2-choices').css({
'border-bottom-left-radius': '5px', // or whatever
'border-bottom-right-radius': '5px', // or whatever
});
});
I think this will cause a problem, though, for any other Select2 combo boxes visible on the same page.
In order to add background color to container you have to put the rule to #s2id_combo. The problem is that ul.select2-choices already has a background and it's over container so you have to add:
ul.select2-choices { background: green !important; }

Why the box disappear immediately?

I want the mouseover on the coverImg then show the coverInfo
the coverInfo show the title and the description of the image
then the coverInfo do show
but I want the coverInfo stay and clickable when mouserover on itself
but it disappear immediately.
So what's the point I have missed?
The HTML
<div class="workshop_img">
<div class="coverInfo"></div>
<a href="#">
<span class="coverImg" style="background-image:url('images/work/show1.jpg')" title="Chictopia "></span>
</a>
The CSS:
.coverInfo {
position:absolute;
width: 200px;
height:200px;
background:rgba(0,0,0,0.5);
top:30%;
left:30%;
display:none;
}
see the jQuery code
$(function() {
$(".coverImg").each(function() {
//make the background image move a little pixels
$(this).css({
'backgroundPosition' : "-40px 0"
}).mouseover(function() {
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
}, {
duration : 90
});
//shwo the info box
var content = $(this).attr("title");
$("<div class='coverInfo'></div>").text(content).prependTo($(this).parent()).fadeIn("fast");
}).mouseout(function() {
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
}, {
duration : 200,
});
$(this).parent().find(".coverInfo").stop().fadeOut("fast");
})
})
});
</div>
EDIT:
I have searched a lot and find something similar, I took them and the answer given below together to solve my problem, here is the code:
$(function() {
$(".coverImg").css({
'backgroundPosition' : "-40px 0"
}).mouseenter(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : " -20px -60px "
},90);
info.show();
}).mouseleave(function() {
var box = $(this).parents(".workshop_img").find(".coverInfo");
var content = $(this).attr("title");
var info = box.text(content);
$(this).stop().animate({
'backgroundPosition' : "-40px 0"
},200);
info.stop().hide();
});
});
It has just been clean, but do not work fine.
What's the problem?
The new box shows immediately because it is not initially marked as hidden. .fadeIn() only fades in something that is initially not showing.
You can make it initially not visible like this:
$("<div class='coverInfo'></div>").text(content).hide().prependTo($(this).parent()).fadeIn("fast");
You also can get rid of the .each() iterator you're using. You don't need it. You can just use:
$(".coverImg").css(...).mouseover(...).mouseout(...);
You don't need the .each() at all.
I'd also suggest you use .hover(fn1, fn2) instead of .mouseover(fn1) and .mouseout(fn2).
And, it looks like you are creating a new object and inserting it on every mouseover event such that multiple such objects will pile up in the page. You should either .remove() the object in the mouseout function or you should reuse a previously existing element if it exists in the element rather than creating more and more of them.
Sometimes when you are using the events for mouse hovering and you are also changing the page, the change to the page can cause the element to lose the mouse hover which then hides the change to the page and then it all starts over again. I can't tell for sure if that is happening in your case (I'd need a working example to play with to see), but it seems possible.

jQuery: equivalent of .live() for CSS?

How do I add CSS to elements that have been dynamically created?
Here is a simple example of what I would like to do:
$(document).ready(function() {
$('#container').html('<p id="hello">hello world</p>');
// The following line doesn't work.
$('#hello').css("background-color", "#FFF");
});
The reason I want to do this, and I can't think of another way of doing it, is that I want to use background colour on alternate rows of a table that is dynamically generated:
$("#results-table tr:even").css("background-color", "#FFF");
I need to use this line of jQuery specifically for IE8 and below, which don't support nth-child CSS selectors.
Actually, your code does work. You might want to check if you don't have multiple elements by that ID.
Edit:
Here's your code, without duplicate IDs: http://jsfiddle.net/FhTU7/
Final edit:
Your HTML background and element background are both white.
You could instead of directly setting the CSS also just add a class to the even rows
$("#results-table tr:even").addClass("alt");
CSS to set the row colours and then a different set of colours for the alternate rows
<style type="text/css">
tr
{
background: #fff;
color: #000;
}
tr.alt
{
background: #000;
color: #fff;
}
</style>
You could declare the new element as a variable...
$(document).ready(function() {
var $new = $('<p id="hello">hello world</p>');
$new.css({
backgroundColor: "#fff"
})
$('#container').append($new);
});
You could use appendTo...
$(document).ready(function() {
$('<p id="hello">hello world</p>').appendTo('#container').css({
backgroundColor: "#fff"
})
});
However, if you create the elements correctly then you can use the original CSS at the end...
$('#container').append('<p id="hello">hello world</p>');

Possible to toggle/animate between two sizes using jQuery?

Basically I have a small div that is initially styled to 60x60. I have created click event that animates the expansion of the div:
$("#myDiv").click(function () {
$(this).animate(
{
width: "350px",
height: "300px"
}, 500);
}
I would like to reverse this animation if someone clicks the div again. Is there anyway to toggle between the original size and the expanded size (still using the animate function) with each click?
I found the toggleClass function but I don't think this will work with animiate.
You can see a basic fiddle here: http://jsfiddle.net/NS9Qp/
$("#myDiv").toggle(function() {
$(this).stop().animate({
width: "350px",
height: "300px"
}, 500);
}, function() {
$(this).stop().animate({
width: "60px",
height: "60px"
}, 500);
});
Example.
The jQuery toggle() function allows you to define two or more functions to cycle through on each mouse click. In this case, the first one (triggered on the first click) expands the div and the second one (triggered on the second click) resets it. On the third click, it starts back at the first one, and so on.
More about toggle() here.
just to be different :
var size=[];
$("#cornerBox").click(function(){
$(this).width() >= 350 ? size=[60, 60] : size=[350, 300];
$(this).stop().animate({ width: size[0], height: size[1] },500);
});
Fiddle: http://jsfiddle.net/NS9Qp/1/
I ended up using jQuery UI's animated toggleClass effect: http://jqueryui.com/demos/toggleClass/
super simple code:
$('h2').click(function() {
$(this).next().toggleClass("hidden", 1000);
});
Do not hardcode css styles (in my example I used inline css for myDiv element, put this in css files).
<div id="myDiv" style="background:red; width: 60px; height: 60px;"></div>
<script type="text/javascript">
var div = $('#myDiv');
div
.attr('defWidth', div.width())
.attr('defHeight', div.height())
.toggle(function() {
$(this).stop().animate({width: "350px", height: "300px"}, 500);
}, function() {
$(this).stop().animate({width: $(this).attr('defWidth'), height: $(this).attr('defHeight')}, 500);
}
);
</script>
What I do for cases like this, is store a transformation array.
var transforms = { 'height0': 60, 'width0': 60, 'height1': 300, 'width1': 350};
Then, store a toggle between 0 or 1, and use the corresponding values for the animation.
EDIT: combine this with the previous example of toggle, and you've got yourself a solid working solution!

Categories

Resources