I have a text and I want to dynamically shortened the text with “Read More” link using JavaScript. I use the following JavaScript code:
var limitDesc = -1;
function ResponsiveDesc() {
//var limitDesc = 100;
//var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
var chars = $("#ResponsiveDescription").html();
if (chars.length > limitDesc) {
var visiblePart = $("<span> " + chars.substr(0, limitDesc - 1) + " </span>");
var dots = $("<span class='dots'>... </span>");
var hiddenPart = $("<span class='more'>" + chars.substr(limitDesc - 1) + "</span>");
var readMore = $("<span class='read-more'>More</span>");
readMore.click(function () {
$(this).prev().remove(); // remove dots
$(this).next().show(); //show hiddenPart
$(this).remove(); // remove readMore
});
$("#ResponsiveDescription").empty()
.append(visiblePart)
.append(dots)
.append(readMore)
.append(hiddenPart);
}
}
$(document).ready(function () {
if (limitDesc > 0 && $(window).width() < 500) {
ResponsiveDesc();
}
});
The main problem is that I don't what this code to cut my text in the middle of a word or a link. What is the best way to solve this problem ?
I can manually change the "limitDesc" variable on each page but when the content of the page is dynamic, it's impossible.
Thanks you in advance.
You can split the string at the last whitespace before your length limit.
You can determine it using lastIndexOf():
limitDesc = chars.lastIndexOf(" ", limitDesc);
http://www.w3schools.com/jsref/jsref_lastindexof.asp
Related
I used this code to window scroll top in android app. but its scrolling total body. not till to selected form field. I want scroll till to selected form field.
here is my code
var is_keyboard = false;
var is_landscape = false;
var initial_screen_size = window.innerHeight;
window.addEventListener("resize", function() {
var currentHeight = window.innerHeight;
is_keyboard = (window.innerHeight < initial_screen_size);
is_landscape = (screen.height < screen.width);
var keyboardSize = (initial_screen_size - currentHeight);
if (keyboardSize > 0) {
alert("Keyboard is shown! Size is: " + keyboardSize);
} else {
alert("Keyboard is closed!");
}
alert('Screen resized. currentHeight: ' + currentHeight + " - OriginalHeight: " + initial_screen_size);
}, false);
To scroll to selected field you need to set a class or id on that element on capturing the event you need to check the flag on that element and then
find the offset and scroll the document to it.
Hope this helps
if (scroll_flag == ' scroll1'){
var fooOffset = $('#gift').offset(),
destination = fooOffset.top;
console.log(destination);
$(document).scrollTop(destination);
}
I need to open a div at a specific location on the page. When I focus on a textbox the div should be opened(made visible). I am able to do this part. The problem is it opens right underneath the textbox and when there is no scroll on the page, it creates one. I need help in showing the div above the textbox when there is more space on upper half of the page then the lower half of the page. Here is the JSFiddle I have created and if someone can edit it, it would be of too much help to me.
And this is how I am opening the div:
function openDIV(activatorCtl) {
var leftpos = 0;
var toppos = 0;
var sScrollTop = getScrollTop;
var aTag = activatorCtl;
do {
aTag = aTag.offsetParent;
sScrollTop = (aTag.scrollTop > sScrollTop) ? aTag.scrollTop : sScrollTop;
leftpos += aTag.offsetLeft;
toppos += aTag.offsetTop;
} while (aTag.tagName != 'BODY');
document.getElementById("divDetails").style.left = leftpos + "px";
document.getElementById("divDetails").style.top = toppos + 20 + "px";
document.getElementById("divDetails").style.zIndex = "999";
document.getElementById("divDetails").style.visibility = "visible";
}
You mean like this?
https://jsfiddle.net/36vdoaqo/3/
I added an if for when the toppos is bigger than 250 (your divs height)
if(toppos <= 250)
Another tip:
You use this 4 times in a row:
document.getElementById("divDetails")
save this element in an variable to get shorter statements like:
var detailsDiv = document.getElementById("divDetails");
detailsDiv.style.left = leftpos + "px";
detailsDiv.style.zIndex = "999";
EDIT: i did not save the jsfiddle properly.
Currently I have a mostly working script I've hobbled together. I'm doing this in multiple phases to make it as modular as possible.
//This grabs every element on page.
$('body').find('*').each(function(){
//This filters for text nodes only
$(this).contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).each(function(){
//Wraps each text node in a span.
$(this).wrap("<span class='text'></span>")
});
})
//
$('.text').each(function(){
//Splits each text node into a character array and wraps each char in a span.
var test = $(this).text().split('');
var curStr = '';
for(var i = 0; i < test.length; i++){
if(test[i] != " " || test[i] != ''){
curStr = curStr + "<span class='char'>" +test[i] + "</span>";
} else {
curStr = curStr + test[i];
}
}
$(this).html(curStr);
})
My issue come from trying to style the elements at random. I'm using the following code to do so:
setInterval(function(){
$($('.char')[Math.floor((Math.random()*$('.char').length)+1)]).each(function(){
$(this).css('color', 'green');
$(this).css('position', 'absolute');
$(this).css('background-color', 'red');
$(this).animate({
top: $(window).height + 'px'
}, 1000, 'swing', function(){$(this).remove()});
})
}, 100)
The issue with this is, it manages to apply the color styling, but my position and animate don't seem to be working.
The jQuery height() method requires parentheses:
Change this:
top: $(window).height + 'px'
To this:
top: $(window).height() + 'px'
Working Example
I have a text area where I do a countdown on .keyup() but it although it does what it supposed to it lets the user to believe that there id 1 character left to type, yet the length of the text area has reached the limit. Here is my code:
<script>
var w_limit = 3000;
$(document).ready(function(){
$('#comment').keyup(function(e) {
el = $(this);
if(el.val().length >= w_limit){
el.val( el.val().substr(0, w_limit) );
} else {
$("#word-count").text(w_limit-el.val().length + ' characters left');
}
});
});
</script>
Aside from your typos, you need to always run the $("#word-count").text(stuff); part. Here's it working without the else:
var w_limit = 20;
$(document).ready(function () {
$('#comment').keyup(function (e) {
var el = $(this),
val = el.val();
if (val.length >= w_limit){
el.val( val.substr(0, w_limit) );
}
$("#word-count").text(w_limit - el.val().length + ' characters left');
});
});
DEMO: http://jsfiddle.net/eHstm/
(of course, I used a lower w_limit number for testing purposes)
I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.