I have a div of online users which are dynamically inserted:
<div id="users">
<div class="privateMessage" data="John">John</div>
<div class="privateMessage" data="Maria">Maria</div>
<div class="privateMessage" data="Tony">Tony</div>
</div>
Then I have a div for private messages:
<div id="messageBox">
</div>
Now, I'm struggling how to dynamically append a div inside the messageBox when I click on the user.
What I need is this below:
<div id="messageBox">
//when I click on John from users div this below should be appended
<div class="private-chat" data-conversation-between="John"></div>
//when I click on Maria from users div this below should be appended and John above
//will be hidden
<div class="private-chat" data-conversation-between="Maria"></div>
//when I click on Tony from users div this below should be appended and John and Maria
//will be hidden
<div class="private-chat" data-conversation-between="Tony"></div>
</div>
Whatever I tried, the divs inside messageBox get appended more than once.
Can someone help me to solve this with jQuery please?
Link: fiddle
What about something like this?
http://jsfiddle.net/thetimbanks/hfuurcL7/
The click event is delegated since the users can be added to the list dynamically. I also search the messageBox for an existing div for that user in order to not add another one.
Adding code here as to not just link to fiddle:
HTML
<div id="users">
<div class="privateMessage" data-user="John">John</div>
<div class="privateMessage" data-user="Maria">Maria</div>
<div class="privateMessage" data-user="Tony">Tony</div>
</div>
<div id="messageBox">
</div>
js
$("#users").on("click", ".privateMessage", function() {
var user = $(this),
private_chat = $("#messageBox .private-chat[data-conversation-between='" + user.data("user") + "']");
if (private_chat.length == 0) {
private_chat = $('<div class="private-chat" data-conversation-between="' + user.data("user") + '">Chat with ' + user.data("user") + '</div>');
$("#messageBox").append(private_chat);
}
private_chat.show().siblings().hide();
});
After short clarification in the comments, I'm posting a working solution:
$('.privateMessage').on('click', function (e) {
$messageBox = $('#messageBox');
var whoIsIt = $(this).attr('data');
var isAlreadyThere = $messageBox.find('div[data-conversation-between="' + whoIsIt + '"]').length;
if (isAlreadyThere == 0) {
$messageBox.append('<div class="private-chat" data-conversation-between="' + whoIsIt + '"></div>');
}
});
jsfiddle: http://jsfiddle.net/pLe01k57/2/
Basically: check if #messageBox already has conversation (div) with clicked-on user, and if not - append it there.
How about this?
$('.privateMessage').on('click', function (e) {
var whoIsIt = $(this).attr('data');
$('#messageBox').append('<div class="private-chat" data-conversation-between="' + whoIsIt + '"></div>');
$(this).unbind();
});
https://jsfiddle.net/lemoncurry/5cq2sw8m/1/
Basically bardzusny's solution above plus a $(this).unbind().
Hope it does what you are expecting .Can check data-attribute before appending div's.
$('.privateMessage').on('click', function(e) {
var isPresent = false;
var whoIsIt = $(this).attr('data');
$('#messageBox .private-chat').each(function(index, element) {
if ($(this).attr('data-conversation-between') == whoIsIt) {
isPresent = true;
}
});
if (!isPresent) {
$('#messageBox').append('<div class="private-chat" data-conversation-between="' + whoIsIt + '"></div>');
}
});
.private-chat {
height: 20px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="users">
<div class="privateMessage" data="John">John</div>
<div class="privateMessage" data="Maria">Maria</div>
<div class="privateMessage" data="Tony">Tony</div>
</div>
<div id="messageBox"></div>
You should avoid using data attribute in this way.
Read more about .data() attribute
HTML:
<div id="users">
<div class="privateMessage" data-selected="" data-who="John">John</div>
<div class="privateMessage" data-selected="" data-who="Maria">Maria</div>
<div class="privateMessage" data-selected="" data-who="Tony">Tony</div>
</div>
<div id="messageBox"></div>
Script:
$("#users").on("click", '.privateMessage', function () {
if(!$(this).data('selected')){
$(this).data('selected', 'selected');
// do not use '.attr()', use natvie jQuery '.data()'
var $msgTo = $(this).data('who');
$("#messageBox").append("<div class='private-chat' data-conversation-between=" + $msgTo + ">"+$msgTo+"</div>");
}
});
DEMO
Alternatively, you could just use .one() event, and reactivate it later for specific button (f.ex. after the person was removed from the chat):
function singleClick(el) {
$(el).one("click", function () {
var $msgTo = $(this).data('who');
$("<div class='private-chat' data-conversation-between=" + $msgTo + ">"+$msgTo+"</div>").appendTo("#messageBox");
});
}
singleClick('.privateMessage');
DEMO (with delete example using .one())
Related
I'm trying the count the total number of divs clicked and exactly which ones were clicked. I'm using an event listener because the onclick is already used. Let me clarify a bit more, first, here's my code:
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
.selected {
background: white;
}
var numClicked = document.querySelectorAll('.wrapper');
numClicked.forEach(numClicked =>
numClicked.addEventListener('click', clickedDivs)
)
function clickedDivs () {
i = 0;
numClicked.forEach(numClicked =>
i++
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + i;
}
What I'm trying to do with my javascript is count how many divs are selected. I'm also trying to tell exactly where ones were clicked. Let's say 1 and 2 were clicked, how do I find those were clicked and total number of divs clicked using js?
What you are doing wrong here is:
You are initialising i within the onClick event fn. which will always reset the value to 0 when ever the div will be clicked.
you are not storing anywhere which div is clicked
You are adding you'r listener on wrapper instead of .square (if you are not trying to get the value of clicked wrappers instead of clicked square)
So you can modify you'r javascript like this
<style>
.square{width: 100px; height: 100px; background: grey;}
.selected {
background: white;
}
</style>
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
<script>
var numClicked = document.querySelectorAll('.square');
numClicked.forEach(numClick => {
numClick.addEventListener('click', clickedDivs)
}
)
var itemsClicked = [] //to store which div is clicked
function clickedDivs (e) {
var value = e.target.innerHTML;
//edit
if(itemsClicked.indexOf(value) != -1) itemsClicked.splice(itemsClicked.indexOf(value), 1)
else
itemsClicked.push(value);
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + itemsClicked.join(",");
}
</script>
edit:
added to code to remove data from the list if already exist.
Rather than attach a handler to each div, you can use 1 window event listener. Give each clickable div an id that contains "clickable" so the event listener can filter out divs you aren't tracking. When you first click a tracked div, set its id as a key within a global object and assign 1 as the value; on additional clicks, increase value by 1.
const clicks = {};
window.addEventListener("click", (e)=> {
const id = e.target.id;
if(!id.includes("clickable"))return;
clicks[id]? clicks[id] += 1 : clicks[id] = 1;
console.log(clicks);
},)
<div class="wrapper">
<div id="clickable1" class="square">1</div>
<div id="clickable2" class="square">2</div>
<div id="clickable3" class="square">3</div>
</div>
My solution, I haven't tested it yet, test it and tell me how we adjusted it.
<div class="wrapper">
<div class="square" id="d-1">1</div>
<div class="square" id="d-2">2</div>
<div class="square" id="d-3">3</div>
</div>
<div id="result"></div>
var count = [];
var wrappers = document.querySelectorAll('.wrapper');
wrappers.forEach(square => square.addEventListener('click',() => onClickwrapperSquare(square.id));
function onClickwrapperSquare(id) {
var result = document.getElementById('result');
if(count.indexOf(id) == -1){
count.push(id);
}else{
count = count.slice(count.indexOf(id)+ 1);
}
result.innerHTML = `Squares selected: ${count.length}`;
}
This can be simply achieved by jQuery.
var count;
$(".square").click(function (){
count = count+1;
$("#dis").html(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class=square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>
<div id="dis"></div>
<section class="refinementsContainer">
<div class="contentfilters">
<div class="refinementContainer refinementmicro" data-dimension="micro"></div>
<div class="refinementContainer refinementcolor" data-dimension="color"></div>
<div class="rightContainer">
<div class="refinementContainer sort"></div>
<div class="refinementContainer refinementSeason"></div>
</div>
</div>
</section>
I have this code. I need to append one class at only one div into the div with class contentfilters. I develop this code but it doesn't work:
$buttonOpenFilter.on(clickEvent, function(e) {
e.stopPropagation();
e.preventDefault();
var $this = $(this).parent();
var classOpen = 'open';
if ($this.hasClass(classOpen)) {
$this.removeClass(classOpen).css('max-height', 30);
} else {
$this.siblings().removeClass(classOpen).css('max-height', 30);
$this.addClass(classOpen).css('max-height', $this.find('ul').height() + 105);
}
});
$('.contentfilters')
https://api.jquery.com/category/selectors/ here you will find everything about selectors.
Hope someone could help!
I have some divs (using bootstrap) like:
<div class="container">
<div class="row" id="r2">
<div class="col-lg-8">
<div class="block-in-div"></div>
</div>
<div class="col-lg-4">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-4">
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="block-in-div"></div>
</div>
</div>
</div>
<div class="col-lg-8">
<div class="block-in-div"></div>
</div>
</div>
</div>
</div>
</div>
</div>
When I click on some div it should randomly get some background color.
When I click on another div, previous should reset its background, and newly clicked div should get its random background.
Whith this issues everything is clear.
I can`t get how to do next: I clicked on div, it changes its colour, I click again and it should become bigger.
Color randomizer:
function getRandomColor() {
var r=Math.floor(Math.random() * (256));
var g=Math.floor(Math.random() * (256));
var b=Math.floor(Math.random() * (256));
var color = '#' + r.toString(16) + g.toString(16) + b.toString(16);
return color;};
Reset background:
function cancelBg() {
let selectedBlocks = $("div.block-in-div");
$.each(selectedBlocks,function(key,value){
selectedBlocks[key].style.background = "none";
});};
Main function:
$(document).ready(function () {
$(".block-in-div").click(function () {
cancelBg();
$(this).css("background", getRandomColor());
});});
Trying smth like:
$(document).ready(function () {
$(".block-in-div").click(function () {
var state = 1;
return function () {
cancelBg();
if(state===1){
$(this).css("background", getRandomColor());
state=2;
}
else if(state===2){
/*$(this).addClass("active");*/
state=1;
}
};
}());});
.active just for test and it is simply:
.active{
height: 100vh;
width: 100vw;
}
Please help!
Be the force with you! :)
You can achieve this by adding a class when the div was clicked first.
$(document).ready(function () {
$(".block-in-div").click(function () {
return function () {
cancelBg();
if(!$(this).hasClass('not-resized')) {
$(this).css("background", getRandomColor());
$(this).addClass('not-resized');
}
else if ($(this).hasClass('not-resized')) {
$(this).addClass("active");
$(this).removeClass('not-resized');
}
};
}());
});
If you need to reset the state on click on other div you can just add $(".block-in-div").removeClass('not-resized'); at the end.
Note 1: Adding active class like you did will have lower priority than the size on original class (add an !important as a temporal fix to see the changes or even better... make a stronger selector).
Note 2: If I didn't get the requirements right pls. tell me.
Thanks everyone!
Mold something like JSFiddle
$(document).ready(function () {
$(".block-in-div").click(function () {
if($(this).hasClass('tofull') && !$(this).hasClass('active')){
$(this).addClass("active");
}
else if($(this).hasClass('active')){
$(this).removeClass("active tofull");
$(this).css("background", "none");
}
else{
cancelBg();
let clr = "#"+((1<<24) * Math.random()|0).toString(16);
$(this).css("background", clr);
$(this).addClass("noColor tofull");
}
});
});
Still got some problems with working but got ideas how to fix it.
Problem is: Click block A (become red), click B (yellow), click C (green), click A again - size changes but no background
I have one div .content with two divs inside (.content-1, .content-2).
In the divs that are inside .content, I just want to have a maximum of two paragraphs.
So, when I click in the button "add" I want to add a paragrah inside a div that has only one or zero paragraph, if have 2 I want to create a new div .content-3 and add this paragraph in this third div, and when this third div has two paragraphs I want to create a new div .content-4, and so on..
Im trying to do this, and I already have working the part that I add a paragraph just when a div have 1 or zero paragraph. But now the part that creates a new div if the others already have two, is not working properly.
Do you see why its wrong?
I have here my example working: http://jsfiddle.net/e2f38kgL/1/
html:
<div class="message">
<input type="text" id="input" onclick="clear();" value="text:"><br>
<button id="import" class="btn">add</button>
</div>
<div class="content">
<div class="content-1">
<p>text 1</p>
<p>text 2</p>
</div>
<div class="content-2">
<p>text 1</p>
</div>
</div>
jquery:
$(document).on('click', '.btn', function(){
var input = $("#input").val();
var maxdivSize = 2;
var divContentSize = $(".content > *").length;
$(".content >*").each(function(){
var i = 0;
var numberOfElements = $(this).find("p").length;
if (numberOfElements < 2){
$(this).append("<p> "+ input + "</p>");
}
else{
$(".content").append("<div class='content-"+i+1+"'>"+input+"</div>");
}
i++;
});
});
Try to use this code,
$(document).on('click', '.btn', function () {
var input = $("#input").val();
var divContentSize = $(".content > *").length;
var relDiv = $(".content > div").filter(function () {
return $(this).children().length !== 2;
});
if (relDiv.length) {
relDiv.append("<p> " + input + "</p>");
} else {
$(".content").append("<div class='content-" + (divContentSize + 1) + "'><p>" + input + "</p></div>");
}
});
$(document).on('click', '#input', function () {
$('#input').val('');
});
DEMO
i've tried for several days and i can't get it work.
I want to get the id of div (ui-widget-content) that is the draggable item, when i dropped and click on the div (ui-widget-header) that is the dropped item but i can't get it work.
<script>
$(document).ready(function () {
$("#j1, #j2, #j3, #j4, #j5, #j6").draggable();
$("#p1, #p2, #p3, #p4, #p5, #p6").droppable({
hoverClass: 'ui-state-hover',
helper: 'clone',
cursor: 'move',
drop: function (event, ui) {
$(this).addClass('ui-state-highlight');
$(ui.draggable).addClass('ui-state-highlight');
$(ui.draggable).draggable('enable');
console.log('Dragged: ' + alert(ui.draggable.attr("id")));
}
});
});
$('ui-widget-header').click(function () {
var item_id = ui.item.attr('id');
});
alert('item_id');
//$('.ui-droppable').click(function(){
// var myStringPosition = $('div'); // $(event.target).attr('id');
// $('.ui-droppable').each(function(){
// myStringPosition = $(this)[0].id;
// });
// alert(myStringPosition);
//});
</script>
</head>
<body>
<div id="j1" class="ui-widget-content" data-userid="1">Jogador 1</div>
<div id="j2" class="ui-widget-content">Jogador 2</div>
<div id="j3" class="ui-widget-content">Jogador 3</div>
<div id="j4" class="ui-widget-content">Jogador 4</div>
<div id="j5" class="ui-widget-content">Jogador 5</div>
<div id="j6" class="ui-widget-content">Jogador 6</div>
<div id="p1" class="ui-widget-header"><p>Posicao 1</p></div>
<div id="p2" class="ui-widget-header"><p>Posicao 2</p></div>
<div id="p3" class="ui-widget-header"><p>Posicao 3</p></div>
<div id="p1" class="ui-widget-header"><p>Posicao 4</p></div>
<div id="p2" class="ui-widget-header"><p>Posicao 5</p></div>
<div id="p3" class="ui-widget-header"><p>Posicao 6</p></div>
</body>
</html>
UPDATE 3: It doesn't look like there is a method to determine which "draggable" item is contained within the droppable. You will have to have a method to remember what was dropped into the container. The data() function on a jquery object is a good method for this.
In the drop function:
var itemId = $(ui.draggable).attr("id");
$(this).data('dropped', itemId);
In the click callback use:
if ($(item).data('dropped'))
{
alert($(item).data('dropped'));
}
NOTE: This will only remember the most recently dropped item and will not remove it once it's dropped into a new container - that should be straightforward to implement.
UPDATE 2: The following should provide an alert with the id of the draggable item. I put the conditional in there to determine if it were moved into the container at the bottom.
$('.ui-widget-content').click(function (event) {
var item = event.target;
if (item.offsetTop >= 140)
{
alert(item.id);
}
});
new fiddle: http://jsfiddle.net/KLLCg/7/
UPDATE: It looks like you wanted something different. If you just want the ID of the destination container you should be able to get it using event.target.id
drop: function (event, ui) {
$(this).addClass('ui-state-highlight');
$(ui.draggable).addClass('ui-state-highlight');
$(ui.draggable).draggable('enable');
var itemId = $(ui.draggable).attr("id");
var destId = event.target.id ;
var message = '"' + itemId + '" was dragged to "' + destId + '"';
alert(message);
console.log(message);
}
see updated fiddle: http://jsfiddle.net/KLLCg/6/
ORIGINAL ANSWER
First - you should put your click handler inside the document.ready. I think you might be having a problem because the event target object will be whatever was clicked and the <p> element doesn't have an id. If I understand your problem the following code may work.
$('.ui-widget-header').click(function (event) {
var item = event.target;
if (item.nodeName == 'P') {
item = item.parentNode;
}
alert(item.id);
});
jsfiddle example: http://jsfiddle.net/KLLCg/3/
Try this one
You just have to store drag object id into "dragId".
<!DOCTYPE html>
<link href='../../css/style.css' rel='stylesheet' type='text/css'/>
<script type="text/javascript" src = "js/jquery.min.js"></script>
<script type="text/javascript" src = "js/jquery-ui.min.js"></script>
<script type="text/javascript" src = "js/jquery-ui.js"></script>
<head>
<style>
.dragAndDrop
{
}
.dragBoxStyle
{
position:absolute;
left:170px;
top:100px;
}
.dropBoxStyle
{
position:absolute;
left:170px;
top:300px;
}
.dragImageStyle
{
}
.dropImageStyle
{
}
</style>
<script>
var dragId;
$(function()
{
$(".dragImageStyle").draggable();
$(".dragImageStyle").mousedown(function()
{
dragId = (this.id);
});
$( ".dropImageStyle" ).droppable(
{
drop: function( event, ui )
{
alert("Droped on "+this.id+" : "+dragId);
}
});
});
</script>
</head>
<body>
<div id = "dragAndDrop">
<div id = "bg">
<img src = "images/BG.jpg"></img>
<div>
<div id = "dropTiles" class = "dropBoxStyle">
<img id = "drop1" class = "dropImageStyle" src = "images/Tab1_V.jpg"><img>
<img id = "drop2" class = "dropImageStyle" src = "images/Tab2_V.jpg"><img>
<img id = "drop3" class = "dropImageStyle" src = "images/Tab3_V.jpg"><img>
<img id = "drop4" class = "dropImageStyle" src = "images/Tab4_V.jpg"><img>
</div>
<div class = "dragBoxStyle">
<img id = "dragBox1" src = "images/BlankBox.png"><img>
<img id = "dragBox2" src = "images/BlankBox.png"><img>
<img id = "dragBox3" src = "images/BlankBox.png"><img>
<img id = "dragBox4" src = "images/BlankBox.png"><img>
</div>
<div id = "dragTiles" class = "dragBoxStyle">
<img id = "drag1" class = "dragImageStyle" src = "images/Tab1_N.jpg"><img>
<img id = "drag2" class = "dragImageStyle" src = "images/Tab2_N.jpg"><img>
<img id = "drag3" class = "dragImageStyle" src = "images/Tab3_N.jpg"><img>
<img id = "drag4" class = "dragImageStyle" src = "images/Tab4_N.jpg"><img>
</div>
</div>
</body>