Only drop to element that is seen - javascript

I have the following:
I am trying to set it up so that when you drag the item, it only gets dropped to the div element which you can see, and is not covered up.
So I used this js:
$(".draggable").draggable({
helper: "clone"
})
$("#bottom, .draggable").droppable({
drop: function(event, ui) {
var $this = $(this),
$dragged = $(ui.draggable);
$this.append($dragged.clone());
},
hoverClass: "dragHover"
})​
But it drops the element in both places even though only one of the drop zones is not visible!
How do I fix it so that this does not happen?
Fiddle: http://jsfiddle.net/maniator/Wp4LU/
Extra Info to recreate the page without the fiddle:
HTML:
<div id="top">
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
<div class="draggable">
Lorem ipsum dolor sit amet
</div>
</div>
<div id="bottom"></div>
CSS:
.draggable {
border: 1px solid green;
background: white;
padding: 5px;
}
.dragHover{
background: blue;
}
#top {
height: 500px;
overflow-y: scroll;
}
#bottom {
height: 150px;
overflow-y: scroll;
border: red solid 4px;
}
​

Try setting with accept function.
The working demo.
$("#bottom, .draggable").droppable({
drop: function(event, ui) {
var $this = $(this),
$dragged = $(ui.draggable);
$this.append($dragged.clone());
},
accept: function () {
var $this = $(this), divTop= $("#top");
if ($this.is(".draggable")) {
return $this.offset().top < divTop.offset().top + divTop.height() ;
}
return true;
},
hoverClass: "dragHover"
})​;​

If I got you right - this one should solve your problem - http://jsfiddle.net/Wp4LU/60/
Also you could write custom accept function - http://jqueryui.com/demos/droppable/#option-accept
Code:
var draggableList = $('#top');
$(".draggable").draggable({
helper: "clone"
});
$("#bottom, .draggable").droppable({
drop: function(event, ui) {
var $this = $(this),
$dragged = $(ui.draggable);
if ($this.hasClass("draggable")) {
if ($this.position().top >= draggableList.height() ||
$this.position().top + $this.outerHeight() >=
draggableList.height())
return;
}
$this.append($dragged.clone());
},
hoverClass: "dragHover"
})​;​

According to the sources (jquery.ui.droppable.js), the drop operation will search for every eligible droppable and apply the drop function to every one that intersects with it:
drop: function(draggable, event) {
var dropped = false;
$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
if(!this.options) return;
if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
dropped = this._drop.call(this, event) || dropped;
(Old versions had the last "OR" condition reversed, so it would only apply to a single droppable. Try your fiddle using jQuery 1.5.2 / jQuery UI 1.8.9, and see that it only drops to one element, albeit the "wrong" one...)
And every tolerance mode currently implemented in the $.ui.intersect function only take into account the (x,y) coordinates:
switch (toleranceMode) {
case 'fit':
return (l <= x1 && x2 <= r
&& t <= y1 && y2 <= b);
break;
case 'intersect':
return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
break;
...
So, unless someone adds a z-index aware tolerance mode, your only option is to work around the issue somehow. I'd suggest first adding every droppable candidate to a set and, when it's time to drop, select only the one that is "closest" to the screen:
$("#bottom, .draggable").droppable({
over: function(event, ui) {
if ( !ui.draggable.data("drop-candidates") )
ui.draggable.data("drop-candidates",[]);
ui.draggable.data("drop-candidates").push(this);
},
out: function(event, ui) {
var that = this,
candidates = ui.draggable.data("drop-candidates") || [];
ui.draggable.data("drop-candidates", $.grep(candidates, function(e) {
return e != that;
});
},
drop: function(event, ui) {
var $this = $(this),
$dragged = $(ui.draggable);
var candidates = $.data("drop-candidates").sort(closestToScreen);
if ( candidates[0] == this )
$this.append($dragged.clone());
},
hoverClass: "dragHover"
})​
Now, implementing the closestToScreen comparator is the tricky part. The W3C CSS Specification describes how rendering engines should sort elements to paint, but I wasn't able to find so far an easy way to access this information. I also asked this question here at SO, maybe someone will find a good way.
P.S. If modifying the jQuery UI source is an option, you could try implementing a z-index aware tolerance mode using document.getElementFromPoint, as this answer to said question suggested:
var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
switch (toleranceMode) {
...
case 'z-index-aware':
return document.elementFromPoint(x1,y1) == droppable;
break;
(that would ensure only the element right below the upper-left corner of the draggable would be considered "good enough" as a drop target - not ideal, but better than what we have so far; a similar solution could be adapted to use the mouse pointer coordinates instead)
And, no, you can't use this method with the workaround presented before: at the moment the drop happens, the drag helper is the element closest to the screen... (Edit: d'oh! It wouldn't work if implemented as a tolerance mode either, for the same reason...)

If you just want to drop on element you can see you could change your selector :
$(".draggable:visible").draggable({
helper: "clone"
});
$("#bottom, .draggable:visible").droppable({
drop: function(event, ui) {
var $this = $(this),
$dragged = $(ui.draggable);
$this.append($dragged.clone());
},
hoverClass: "dragHover"
})​;
Or when you hide an element change its' draggable class by something else.

Related

Using .split to split up content in a string

Hi I've got a string where I want to spilt up the content "ipsum dolar" and wrap it into a span tag and have the background change to red. My code does this but it wraps the two words into separate span tags. How would i amend my code to wrap them into one span tag together? Any help on this would be appreciated.
var findWords = 'ipsum dolor';
var elem = document.querySelectorAll('p.content');
elem.forEach(function(el) {
el.innerHTML = el.textContent.split(' ').map(function(i) {
return findWords.indexOf(i) > -1 ? '<span class="matched">' + i + '</span>' : i;
}).join(' ');
});
.matched {background: red;}
<p class="content"> Lorem ipsum dolor sit amet</p>
<p class="content"> Lorem ipsum dolor sit amet</p>
Using .replace() will be better in this case:
var findWords = 'ipsum dolor';
var elem = document.querySelectorAll('p.content');
elem.forEach(function(el) {
el.innerHTML = el.textContent.replace(new RegExp(findWords, 'g'), '<span class="matched">' + findWords + '</span>');
});
.matched {background: red;}
<p class="content"> Lorem ipsum dolor sit amet</p>
<p class="content"> Lorem ipsum dolor sit amet ipsum dolor</p>

JavaScript: How to generate nested ordered list

How to generate nested ordered lists from the following content? I have searched the forum and worked for a few hours now to generate ordered lists based on the different classes from the source content. The content may have up to 6 nesting
level.
What I need is to generate ordered lists based on the different classes. As shown in the sample content to get something like below outlined example content.
.firstclass => 1.
.secondclass => 1.
.thirdclass => 1.
.fourthclass => 1.
The code:
var cheerio = require('cheerio');
var $ = cheerio.load('<h1 class="header">First Header</h1><p class="firstclass">First Lorem ipsum dolor sit.</p><p class="firstclass">First Qui consequatur labore at.</p><p class="secondclass">Second Lorem ipsum dolor sit amet.</p> <p class="thirdclass">Third Lorem ipsum dolor sit amet.</p><p class="thirdclass">Third Molestias optio quasi ipsam unde!</p><p class="secondclass">Second Lorem ipsum dolor sit amet, consectetur.</p><p class="fourthclass">Fourth Lorem ipsum dolor sit.</p><p class="firstclass">First Lorem ipsum dolor sit amet.</p>', {
normalizeWhitespace: true,
xmlMode: true,
decodeEntities: false,
});
var myContent = $('p').each(function() {
var para = $(this).text();
return para;
});
var olClass = ['.firstclass', '.secondclass', '.thirdclass', '.fourthclass'];
function arrToOl(arr) {
var ol = $('<ol />'),
li = $('<li />');
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
li.append(arrToOl(arr[i]));
} else {
li = $('<li />');
li.append($(arr[i]));
ol.append(li);
}
}
return $.html(ol);
}
console.dir(arrToOl(olClass));
The above code produces the following:
'<ol><li><p class="firstclass">First Lorem ipsum dolor sit.</p><p class="firstclass">First Qui consequatur labore at.</p><p class="firstclass">First Lorem ipsum dolor sit amet.</p></li><li><p class="secondclass">Second Lorem ipsum dolor sit amet.</p><p class="secondclass">Second Lorem ipsum dolor sit amet, consectetur.</p></li><li><p class="thirdclass">Third Lorem ipsum dolor sit amet.</p><p class="thirdclass">Third Molestias optio quasi ipsam unde!</p></li><li><p class="fourthclass">Fourth Lorem ipsum dolor sit.</p></li></ol>'
The desired result should be:
<ol>
<li>
<p class="firstclass">First Lorem ipsum dolor sit.</p>
</li>
<li>
<p class="firstclass">First Qui consequatur labore at.</p>
</li>
<li>
<p class="firstclass">First Lorem ipsum dolor sit amet.</p>
<ol>
<li>
<p class="secondclass">Second Lorem ipsum dolor sit amet.</p>
</li>
<li>
<p class="secondclass">Second Lorem ipsum dolor sit amet, consectetur.</p>
<ol>
<li>
<p class="thirdclass">Third Lorem ipsum dolor sit amet.</p>
</li>
<li>
<p class="thirdclass">Third Molestias optio quasi ipsam unde!</p>
<ol>
<li>
<p class="fourthclass">Fourth Lorem ipsum dolor sit.</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
Your help is really appreciated.
Here's what I got.
let array = ["a", "b", "c", "d"];
var nested;
function create_nested()
{
var old_ol;
for (let i = 0; i < array.length; i++)
{
let new_ol = document.createElement("ol");
let new_li = document.createElement("li");
new_li.innerHTML = array[i];
new_ol.appendChild(new_li);
if (i !== 0)
{
let nest_li = document.createElement("li");
let new_p = document.createElement("p");
new_p.innerHTML = "new stuff";
nest_li.appendChild(new_p);
nest_li.appendChild(old_ol);
new_ol.appendChild(nest_li);
}
old_ol = new_ol;
nested = new_ol;
}
}
create_nested();
document.getElementById('main').appendChild( nested);
<div id='main'>
</div>
This is just an example and not exactly the data that you have (you can figure that out).
What's happening is that I'm creating new elements using document.createElement, after which I am inserting them into their corresponding ol/li using appendChild.
The most important part is the if (i !== 0) (Change this to suit whether you want to start from the beginning or end of your array). This is the part where I am creating the nests.
I am creating a new li, which has the <p> and the old_ol which is the nesting li. So what this function is doing, is creating the innermost ol, and expanding it upward.
There might be a clear/better way of doing this, but this is as far as I know in vanilla JS. I hope everything is clear enough.

How to show child element when other child element is overflowing with JQuery

I have recently been working on a comment feature. By default, the height of the paragraph element containing the text is 80px. Overflow is set to hidden.
I have another button (labelled "See More") that expands the paragraph by changing height to 'auto'. This button should only be visible if the paragraph content is overflowing the default 80px height. Otherwise the button must not be displayed.
I have tried to do this with a javascript for loop and some JQuery code, though it doesn't work as it should. It shows or hides the button for all comment sections.
Here is the html:
<div class="commentOwnerPost">
<div class="commentPostHeader">
<h4 class="commentOwnerName">NavyFoxKid</h4>
<h4 class="commentPostDate">3 days ago</h4>
</div>
<p class="commentText"> lorem ipsum dolor sit amet consectur lorem ipsum dolor sit amet consectur
amet consectur lorem ipsum dolor sit amet consectur lorem ipsum
</p>
<div class="commentPostFooter">
<a class="btnReply">Reply</a>
<a class="btnSeeMore">See More</a>
</div>
</div>
Here is the JavaScript:
$(document).ready(function(){
var element = $('.commentOwnerPost');
for(i=0; i < element.length; i++){
var commentText = $(element[i]).children('.commentText');
if ($(commentText).offsetHeight < $(commentText).scrollHeight) {
$parent = $(commentText).parent('.commentOwnerPost');
$parent.find('.btnSeeMore').hide();
console.log('Comment text not overflowing ');
} else {
$parent = $(commentText).parent('.commentOwnerPost');
$parent.find('.btnSeeMore').show();
console.log('Comment text overflowing ');
}
$('.btnSeeMore').click(function(){
});
}
});
Thanks for taking the time to read. Any help would be appreciated.
It works perfectly for me, I simplify your code:
$(document).ready(function(){
var elements = $('.commentOwnerPost');
elements.each(function() {
var el = $(this).find('.commentText').get(0);
if(el.offsetHeight < el.scrollHeight) {
$(this).find('.btnSeeMore').show();
} else {
$(this).find('.btnSeeMore').hide();
}
});
});
.commentText { max-height: 25px; overflow:hidden;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="commentOwnerPost">
<div class="commentPostHeader">
<h4 class="commentOwnerName">NavyFoxKid</h4>
<h4 class="commentPostDate">3 days ago</h4>
</div>
<p class="commentText"> lorem ipsum dolor sit amet consectur lorem ipsum dolor sit amet consectur
amet consectur lorem ipsum dolor sit amet consectur lorem ipsum
</p>
<div class="commentPostFooter">
<a class="btnReply">Reply</a>
<a class="btnSeeMore">See More</a>
</div>
</div>
<div class="commentOwnerPost">
<div class="commentPostHeader">
<h4 class="commentOwnerName">NavyFoxKid</h4>
<h4 class="commentPostDate">3 days ago</h4>
</div>
<p class="commentText"> lorem ipsum dolor sit amet.
</p>
<div class="commentPostFooter">
<a class="btnReply">Reply</a>
<a class="btnSeeMore">See More</a>
</div>
</div>

Manipulate html-string variable with javascript

I need to manipulate a string-variable with JavaScript, which has some html-content. I want to search for some elements, change them and wrap these elements with another div-container.
How can I get this:
var myArr = ['Foo', 'Bar'];
var contenthtml = "<p>Foo</p>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem <b>ipsum</b> dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p>
<p>Bar</p>
<p>Lorem ipsum dolor sit amet</p>";
to this:
contenthtml = "<div class='foo'><h1>Foo</h1>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem <b>ipsum</b> dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p></div>
<div class='bar'><h1>Bar</h1>
<p>Lorem ipsum dolor sit amet</p></div>";
You can use a regular expression (similar to my other answer at https://stackoverflow.com/a/21803683/3210837):
var keywordsRegEx = keywords.map(function(x){return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');}).join('|');
var result = str.replace(new RegExp('<p>(' + keywordsRegEx + ')</p>\r\n((?:[ \t]*<p>(?:(?!' + keywordsRegEx + ').)*</p>(?:\r\n)?)*)', 'mgi'), '<div><h1 class="$1">$1</h1>\r\n$2</div>\r\n');
See http://jsfiddle.net/ncu43/1/ for a full example.
What the regular expression does is it matches <p>, one of the keywords, </p>, and then a paragraph (not containing one of the keywords) zero or more times.
I used some DOM to solve this problem. For those who prefer a DOM solution, rather than RegExp:
Append elements in a variable instead of a temporary DOM
This would be a little bit easier with straight-up DOM replacement/wrapping (in fact, I wrote such a solution but re-wrote it when I saw your comment saying you needed string input), but here's a solution using just a string as input:
var myArr = ['Foo', 'Bar'];
var contenthtml = '<p>Foo</p>\n'
+ '<p>Lorem ipsum dolor sit amet</p>\n'
+ '<p>Lorem <b>ipsum</b> dolor sit amet</p>\n'
+ '<p>Lorem ipsum dolor sit amet</p>\n'
+ '<p>Bar</p>\n'
+ '<p>Lorem ipsum dolor sit amet</p>';
var elements = $.parseHTML(contenthtml);
var tmp = '';
$.each(elements, function(index, element) {
$.each(myArr, function(i, e) {
if (element.innerHTML == e) {
elements[index] = $('<h1>' + e + '</h1>').get(0);
return;
}
});
if (elements[index].outerHTML) {
tmp += elements[index].outerHTML + '\n';
}
});
contenthtml = '<div class="foo">' + tmp + '</div>';
console.log(contenthtml);
jsfiddle

Separately processing wrapped lines using jQuery

I am looking for a way to separately process the lines in a <div> that are wrapped due to a narrow width. That is, if my text is "Lorem ipsum dolor sit amet lorem \n ipsum dolor sit amet" and it is seen as below:
Lorem ipsum dolor
sit amet lorem
ipsum dolor sit
amet
Then I should be able to encapsulate each 'line' in a, say, <span> tag, such as:
<span id="line0">Lorem ipsum dolor<span>
<span id="line1">sit amet lorem</span>
... etc.
Edit: We can assume that the width and height of the div is fixed and known.
I couldn't find a proposed solution, if any exists; although there is a good suggestion for counting the lines for a fixed line-height: How to check for # of lines using jQuery
Starting with this:
<div class="narrow">Lorem ipsum dolor sit amet lorem ipsum dolor sit amet</div>
css:
.narrow {
width:60px;
}
Insert some placeholders where there are spaces:
$('.narrow').html($('.narrow').html().replace(/ /g,"<span class='count'> </span>"))
Determine the y-position of each placeholder:
$('.narrow .count') .each(function() {
var myPos = $(this).position()
alert(myPos.top)
})
From there you should be able to figure out where the start/end points of each line based on its y-position.

Categories

Resources