jQuery Select Visible Elements After Append - javascript

I'm trying to select visible children after appending them into a temp div.
But I got undefined. I've prepared a pen here: codepen
function createTemp() {
var innerObj = $('.main');
var el = $('<div class="doc-temp" style="display: none;"><div class="temp2">' + innerObj.html() + '</div></div>');
$('body').append(el);
var visible = el.children(':visible');
return visible;
}
console.log(createTemp().html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<span>Well</span> Hello
<span>Three</span> Hi Hello
<span style="display: none;">Four</span>
<span>Five</span> See you
</div>

If your element is hidden it will NOT have ANY :visible descendants!
Also you need the HTML of main
If you want the children that WOULD be visible if the PARENT was, you can do this:
function createTemp() {
var innerObj = $('.main').html();
var el = $('<div class="doc-temp"><div class="temp2"></div></div>');
$("body").append(el);
$(".temp2").append(innerObj);
var children = $(".temp2")[0].childNodes;
return [...children].map(el => {
if (el.getAttribute) {
return el.getAttribute("style") === "display: none;" ? null : el.outerHTML
}
return el === null ? null : el.textContent;
})
}
$("#ta").val(createTemp().join(""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<span>Well</span> Hello
<span>Three</span> Hi Hello
<span style="display: none;">Four</span>
<span>Five</span> See you
</div>
<textarea rows="100" cols="100" id="ta"></textarea>

Modify your function to below:
function createTemp(){
var innerObj = $('.main');
var el = '<div class="doc-temp" style="display: none;"><div class="temp2">' + innerObj.html() + '</div></div>';
$('body').append(el);
var visible = $('.main').find(':visible');
return visible;
}
After this change, you can iterate through the visible array. Use $.each for this iteration process.

Related

how to delete a particular element in javascript

I want to make a function to create a new box when I click 'add new box' button and after that, it will also able to delete the box when I click the particular delete button which is related with the box. How to make the function in javascript? Should I save in an array for every new element that it creates?
My code:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px" ></div>
</div>
</div>
<button onclick="addBox();">Add box</button>
<button onclick="deleteBox();">Delete box</button>
I wanted to be like this!
You need to target the button element using this as an argument on the deleteBox() function and then the parent of the button by using parentNode and then apply remove() method on it:
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(e){
e.parentNode.remove()
}
.content{
width: 100px;
height: 100px;
margin-bottom: 10px;
background: #F5A623;
display: inline-block;
vertical-align: middle;
}
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content" style="width:100px;height:100px;background:orange;margin:1px"></div>
<button onclick="deleteBox(this);">Delete</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
As a sidenote, I strongly recommend you to have unique ids on elements.
Try this,
<div id="container">
<div id="target" class="foo" val="demo">
<div class="content">aaa</div>
<button onclick="deleteBox(this);">Delete box</button>
</div>
</div>
<button onclick="addBox();">Add box</button>
function addBox() {
var el = document.getElementById('target');
var clone = el.cloneNode(true);
var frame = document.getElementById('container');
var attr = document.createAttribute('val');
attr.value = 'demo';
el.setAttributeNode(attr);
frame.appendChild(clone);
}
function deleteBox(obj){
obj.parentElement.remove();
}
JQuery:
function deleteBox(){
$( "#target" ).remove();
}
Javascript:
function deleteBox(){
document.getElementById('target').remove()
}
This is alternative example, You can try in your code :)
var sentenceIndex = 1;
function addSentence() {
var n = sentenceIndex;
var html = '<div class="form-item-wrap" id="sentencebox' + n + '">'+
'<div class="form-item">'+
'<input class="form-control" type="text" id="sentence'+n+'" name="sentence[' + n + ']">'+
'</div>'+
'<div class="course-region-tool">'+
'<a href="javascript:void(0);" onclick="removeSentence('+n+');" class="delete" title="delete">'+
'<i class="icon md-recycle"></i></a></div></div>';
$("#addSentenceDiv").append(html);
sentenceIndex = sentenceIndex + 1;
}
function removeSentence(id) {
console.log(id);
$("#sentencebox"+id).remove();
}

Highlight results when searching divs

I have a div setup like this:
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">lorem ipsum test test1 testing</div>
</div>
<div class="entry">
<div class="title">attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
And I allow the user to search the divs with:
jQuery(document).ready(function() {
jQuery("#search").on("keyup click input", function () {
var val = jQuery(this).val();
if (val.length) {
jQuery(".entry").hide().filter(function () {
return jQuery('.title, .description',this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
}).show();
}
else {
jQuery(".entry").show();
}
});
});
Works great, try jsFiddle.
My question is, how can I highlight the search terms? For example, if the user searches for test, I want to wrap the text test into <span> tags.
EDIT: Note that I know how to search/replace text, but I can't seem to make it work properly with my search function.
Optimised solution
After all the issues discussed in comments and trying to optimise the solution so it won't have any lack for eventual bugs, I refactored the code and optimised it:
$(document).ready(function() {
$("#search").on("keyup click input", function() {
var val = jQuery(this).val();
var regExp = new RegExp(val, 'ig');
var reg = new RegExp('<span class="highlight">(.+)<\/span>', 'ig');
if (val.length) {
$(".entry").hide().filter(function() {
var found = $('.title, .description', this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
if (val.length > 3) {
$('.title, .description', this).each(function(k, v) {
if ($(v).text().match(regExp)) {
$(v).html($(v).text().replace(regExp, '<span class="highlight">$&</span>'));
} else {
$(v).html($(v).text().replace(reg, '$&'));
}
});
} else {
$('.title, .description', this).each(function(k, v) {
$(v).html($(v).text().replace(reg, '$&'));
});
}
return found;
}).show();
} else {
$('.title, .description').each(function(k, v) {
$(v).html($(v).text().replace(reg, '$&'));
});
$(".entry").show();
}
});
});
.highlight {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">lorem ipsum test test1 testing</div>
</div>
<div class="entry">
<div class="title">attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
It loops over the elements and use a RegExp with a matching group and if the iterated element content matches the Regex replace the matched text with the same content wrapped in a span, otherwise just set the content to its original form.
Original Answer
This is how you should do it:
var val = jQuery(this).val();
if (val.length) {
$(".entry").hide().filter(function() {
var found = $('.title, .description', this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
var regExp = new RegExp(val, 'ig');
$('.title, .description', this).each(function(k, v) {
if ($(v).text().toLowerCase().indexOf(val.toLowerCase()) != -1) {
var newHTML = $(v).text().replace(regExp, '<span class="highlight">$&</span>');
$(v).html(newHTML);
}
});
return found;
}).show();
} else {
$(".entry").show();
}
You need to loop over the elements and use a RegExp with a matching group and if this element content matches your Regex replace the matched text with the same content wrapped in a span.
Demo:
This is a working Demo:
$(document).ready(function() {
$("#search").on("keyup click input", function() {
var val = jQuery(this).val();
if (val.length) {
$(".entry").hide().filter(function() {
var found = $('.title, .description', this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
var regExp = new RegExp(val, 'ig');
$('.title, .description', this).each(function(k, v) {
if ($(v).text().toLowerCase().indexOf(val.toLowerCase()) != -1) {
var newHTML = $(v).text().replace(regExp, '<span class="highlight">$&</span>');
$(v).html(newHTML);
}
});
return found;
}).show();
} else {
$('.title, .description').each(function(k, v) {
var reg = new RegExp('<span class="highlight">(.+)<\/span>', 'ig');
var newHTML = $(v).text().replace(reg, '$&');
$(v).html(newHTML);
});
$(".entry").show();
}
});
});
.highlight {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">lorem ipsum test test1 testing</div>
</div>
<div class="entry">
<div class="title">attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
Edit:
This is a Demo that highlights sentences only if more than 2 letters are typed:
$(document).ready(function() {
$("#search").on("keyup click input", function() {
var val = jQuery(this).val();
if (val.length) {
$(".entry").hide().filter(function() {
var found = $('.title, .description', this).text().toLowerCase().indexOf(val.toLowerCase()) != -1;
var regExp = new RegExp(val, 'ig');
if (val.length > 2) {
$('.title, .description', this).each(function(k, v) {
if ($(v).text().toLowerCase().indexOf(val.toLowerCase()) != -1) {
var newHTML = $(v).text().replace(regExp, '<span class="highlight">$&</span>');
$(v).html(newHTML);
}
});
} else {
$('.title, .description').each(function(k, v) {
var reg = new RegExp('<span class="highlight">(.+)<\/span>', 'ig');
var newHTML = $(v).text().replace(reg, '$&');
$(v).html(newHTML);
});
}
return found;
}).show();
} else {
$('.title, .description').each(function(k, v) {
var reg = new RegExp('<span class="highlight">(.+)<\/span>', 'ig');
var newHTML = $(v).text().replace(reg, '$&');
$(v).html(newHTML);
});
$(".entry").show();
}
});
});
.highlight {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">lorem ipsum test test1 testing</div>
</div>
<div class="entry">
<div class="title">attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
Try with contains(text) instead of filter() .initially hide the All div .Then Show only the text contains div .And apply the span element to matching letter in the children using new RegExp()
For ignore case sensitive match ig in regex and also added code for case insensitive for contains
Updated Fix with .title, .description on children
jQuery(document).ready(function() {
jQuery("#search").on("input", function() {
var val = jQuery(this).val()
jQuery(".entry").hide()
jQuery(".entry:contains(" + val + ")").show()
jQuery(".entry").each(function() {
if ($(this).find(".title, .description:contains(" + val + ")")) {
$(this).find(".title, .description:contains(" + val + ")").html(function() {
return $(this).text().replace(new RegExp('('+val+')', 'ig'), '<span>$1</span>')
})
}
})
});
})
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
.entry {
background: #fff;
margin-bottom: 10px;
width: 300px;
}
span {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">lorem ipsum test test1 testing</div>
</div>
<div class="entry">
<div class="title">Attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
<div class="entry">
<div>
<div class="title">For nested element on titan</div>
<div>
<div class="description">fullmetal alchemist nested</div>
</div>
</div>
</div>
Try this:
document.getElementById('search').onkeyup = userInput;
document.getElementById('search').onclick = userInput;
document.getElementById('search').oninput = userInput;
var allEntries = document.querySelectorAll('.entry');
function userInput () {
var val = this.value;
for (var i = 0; i < allEntries.length; i++) {
var entryElement = allEntries[i];
var title = entryElement.querySelector('.title');
var description = entryElement.querySelector('.description');
var noHtmlSearchStr = '';
if (title) noHtmlSearchStr += title.innerText;
if (description) noHtmlSearchStr += description.innerText;
if (noHtmlSearchStr.length > 0) {
if (noHtmlSearchStr.toLowerCase().indexOf(val.toLowerCase()) != -1) {
// Remove existing <b> tags.
var regexp1 = new RegExp('(<b>|<\/b>)', 'gi');
if (title) title.innerHTML = title.innerHTML.replace(regexp1, '');
if (description) description.innerHTML = description.innerHTML.replace(regexp1, '');
if (val.length > 3) {
var regexp2 = new RegExp('(' + val + ')(?!>)', 'gi');
if (title) title.innerHTML = title.innerHTML.replace(regexp2, '<b>$1</b>');
if (description) description.innerHTML = description.innerHTML.replace(regexp2, '<b>$1</b>');
}
entryElement.style.display = 'block';
} else {
entryElement.style.display = 'none';
}
}
}
}
.entry {
background: #fff;
margin-bottom: 10px;
width: 300px;
}
<input id="search">
<div class="entry">
<div class="title">hello world test 123</div>
<div class="description">div lorem <span>ipsum</span> test <div>test1</div> testing span</div>
</div>
<div class="entry">
<div class="title">attack on titan</div>
<div class="description">fullmetal alchemist</div>
</div>
<div class="entry"></div>
<div class="entry">
<div class="title">attack on titan</div>
</div>
<div class="entry">
<div class="description">Let's not go to Camelot, 'tis a silly place</div>
</div>
Explanation of JS code
Bind all events to the userInput() function.
Get all elements with the .entry class and store them in allEntries.
Get the user's input and store in val.
Iterate through allEntries.
Get the text to search on from title and description and store in noHtmlSearchStr.
If val matches some part of noHtmlSearchStr then show the entryElement, otherwise hide it.
Remove <b> tags from title and description.
If the length of the user's search (val) is longer than three characters, highlight the matches on the text, otherwise, don't highlight anything.

How to remove attribute found within a variable?

I have
var $imageSelected = '<div style="position: absolute"><span>hello</span></div>';
I need to remove the style attribute form the created variable
I tried:
$imageSelected + "*").removeAttr("style");
and
$imageSelected).find("*").removeAttr("style");
Full code with added replace functionality as per first answer:
$(".grid-item").on("click", function() {
var $imageSelected = $(this).prop('outerHTML');
var $paste = $imageSelected.replace(/style.+"/, '');
$('#usp-custom-4').val(function(_, currentValue) {
return currentValue + $paste
});
});
Using $imageSelected).removeAttr("style"); doesn't work and by using the code above it does remove style yet it is pasting many times the code into the text area, not this clicked only
$('#usp-custom-4') is the textarea id
Clone, remove attr, select the html
$(".grid-item").on("click", function() {
var $imageSelected = $(this).clone().removeAttr("style"),
code = $("<div></div>").append($imageSelected).html();
//code = $imageSelected.prop('outerHTML');
$('#usp-custom-4').val(function(_, currentValue) {
return currentValue + code
});
});
div {
padding: 1em; border: 1px solid black; margin: .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item" style="display:block;">1</div>
<div class="grid-item" style="display:block;">2</div>
<div class="grid-item" style="display:block;">3</div>
<div class="grid-item" style="display:block;">4</div>
<textarea id="usp-custom-4"></textarea>
You can use e.g. replace function.
var $myValue = '<div style="position: absolute"><span>hello</span></div>';
$myValue = $myValue.replace(/ style.+"/, '');
console.log($myValue);

jQuery append to div on click from the different div

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())

jquery ui How to get a id of a draggable item when i click on the droppable item

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>

Categories