i have a following feed from twitter and im making all links clickable and then i want that links which are inside a tag to be short to 30 chars, if its more then 30 chars then show ... after 30 chars
twitter feed
i need to start learning some real javascript from http://javascript.com/java/codes/snippet/search?q=javascript+limit+chars+leading some more text here, so dont remove this.
TO
i need to start learning some real javascript from http://javascript.com/java... some more text here, so dont remove this.
just need to know how can i truncate the inside of tag.
Edited
the link can be anywhere in whole text area.
To truncate a string, have a look at the trunc-prototype method for strings in my answer here. To acquire all links of a page use:
var linksHere = document.getElementsByTagName('a');
loop through your links and shorten the innerHTML of every link if the length is more than you want. Something like:
var i=-1,len = linksHere.length;
while (++i<len){
linksHere[i].innerHTML = linksHere[i].innerHTML.trunc(30);
}
Here's a handy truncating function I use.
// Examples
truncate('abcdefghijklmnopqrstuvwxyz'); // returns 'abcdefghijklmnopqrst...'
truncate('hello there', 15); // returns 'hello there'
truncate('hello there', 5, '...read more...'); // returns 'hello...read more...'
// Truncating method
function truncate(string, length, end)
{
if (typeof length == 'undefined')
{
length = 20;
}
if (typeof end == 'undefined')
{
end = '...';
}
if (string == null)
{
return '';
}
return string.substring(0, length-1)+(string.length > length ? end : '');
}
Related
I'm making a form to fill in and create a pdf through, but I'm facing a problem with text area, I want the user to input text and while writting and pressing space to go back to line like this:
i want it to automatically show in the pdf but instead i get this:
how can i fix it? the code for this is:
<div class="mb-2"><textarea name="element" placeholder="Elements à fournir" class="form-control"></textarea></div>
You need to convert the line breaks from the textarea (\r or \n) into line breaks your PDF can understand (<br /> <div> <li> etc).
a simple PHP way is
$string = nl2br($string);
// converts \n to <br />
If you need to transform those line breaks on the fly (like you're capturing the input and displaying it formatted as the user types), then do it in javascript. Here is a handy function taken from: https://stackoverflow.com/a/7467863/1772933
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Here is an example of how to use that function as the user is typing
$('#TextArea').keypress(function(evt){
$('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
$('#pdfPreviewArea').html($('#TextArea').val()); // copy to #pdfPreviewArea
});
I have a small time url shortner at http://thetpg.tk using a simple php script and MySQL.
What it does is to get the id and matches it in the SQL Database and redirects it to the specified link found in the Database using header().
But if I have a frameset with source as something like http://thetpg.tk redirected link is loaded inside the frame instead of the parent window.
For e.g. look at the page source of
http://thetpgmusic.tk which has the frame source as
http://thetpg.tk/b which further redirects to
http://thepirategamer.tk/music.php .
I want (1) to load (3) as the parent, but just by making changes in the functions in (2) .
So is there a function like
header(Location:http://thepirategamer.tk/music.php, '_parent');
in php, or is there any other way to implement it?
NOTE: I can't change anything in (2).
Thanks in advance ! :)
There are tree solutions that can help you do this:
First solution:
This solution may involve php if you're using echo to generate your html code, when you need to output an a tag, you should make sure to add the atribute target='_parent'
<?php
echo ' Click here ';
?>
problem :
The problem with this solution, is that it doesn't work if you need to redirect in the parent window from a page that you don't own (inside the iframe). The second solution solves this problem
Second solution:
This second solution is totally client-side, wich means you need to use some javascript. you should define a javascript function that addes the target='_parent' in every a tag
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
this.setAttribute('target','_parent');
}
};
Now all you need to do is to call this function when the body is loaded like this
<body onload="init();"> ... </body>
problem:
The problem with this solution, is that if you have a link that contains an anchor like this href="#" it will change the parent window to the child window To solve this problem, you have to use the third solution
Third solution:
This solution is also client-side and you have to use javascript. It is like the second solution except that you have to test if the link is a url to an external page or to an anchor before you redirect. so you need to define a function that returns true if it's a link to an external page and false if it's a simple anchor, and then you'll have to use this function like this
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
if ( is_external_url( this.href ) )
document.location = this.href;
}
};
and you also need to call this function when the body is loaded
<body onload="init();"> ... </body>
don't forget to define is_external_url()
update :
Here is the solution to get the url of the last child, it's just a simple function that looks from frames and iframes inside the paages and get the urls
function get_last_url($url)
{
$code = file_get_contents($url);
$start = strpos($code, '<frameset');
$end = strpos($code, '</frameset>');
if($start===false||$end===false)
{
$start = strpos($code, '<iframe');
$end = strpos($code, '</iframe>');
if($start===false||$end===false)
return $url;
}
$sub = substr($code, $start,$end-$start);
$sub = substr($sub, strpos($sub,'src="')+5);
$url = explode('"', $sub)[0];
return get_last_child($url);
}
$url = get_last_url("http://thetpgmusic.tk/");
header('Location: ' . $url);
exit();
I have the following PHP code:
function word_filter()
{
$tt_tijdelijke = '';
$tt_gestoffeerd = '';
$tt_gemeubileerd = '';
str_replace('tijdelijke', '<span class="incexc-single" tooltip="'.$tt_tijdelijke.'">tijdelijke</span>');
str_replace('gestoffeerd', '<span class="incexc-single" tooltip="'.$tt_gestoffeerd.'">gestoffeerd</span>');
str_replace('gemeubileerd', '<span class="incexc-single" tooltip="'.$tt_gemeubileerd.'">gemeubileerd</span>');
return true;
}
add_filter('wordfilter','word_filter');
I need this to run on every page in the website, replacing all the words with the same word, but inserted in a span. Doing so will allow a tooltip to appear when I mouse over the word.
The mouseover and tooltip already work, but I can't figure out how to get the replace to work on all pages.
How can I best call this function without causing too much page load?
I think you can use javascript split. the code will alert the text, but you can change that and use it for tooltip.
var txt = 'Word*tooltip';
alert(txt.split("*")[1]);
I have recently reading someone code. In his code I see a weird html text written like {VARIABLE} . What is that syntax mean? and how to create it? Thanks
In PHP, there's something called "Complex (curly) syntax" (look for this deeper in the page) where you inject variable's values into strings using {} instead of cutting and concatenating the string.
A similar answer can be found here
Another case is that the HTML could contain that text is when it is used as a template, like this one in CodeIgniter.
You don't initialize it. It's part of their templating engine.
Regardless of how they are doing it, the idea is to find/replace "{VAR}" with the actual data you want.
var songTemplate = "<li class=\"track\"><span class=\"num\">{{TRACKNUM}}.</span>" +
"<span class=\"title\">{{TITLE}}</span>" +
"<span class=\"duration\">{{DURATION}}</span></li>";
var songs = [ { tracknum : 1, title : "Speak to Me/Breathe", duration : "4:13" },
{ tracknum : 2, title : "On the Run", duration : "3:36" },
{ tracknum : 3, title : "Time", duration : "7:01" } ];
function makeTrack (song, template) {
var track = "";
track = template.replace("{{TRACKNUM}}", song.tracknum);
track = template.replace("{{TITLE}}"), song.title);
track = template.replace("{{DURATION}}", song.duration);
return track;
}
function trackList (songs, template) {
var list = "<ul class=\"tracklist\">";
songs.forEach(function (song) {
list += makeTrack(song, template);
});
list += "</ul>";
return list;
}
var songlist = trackList(songs, songTemplate);
parentEl.innerHTML = songlist;
The basic idea, regardless of what language is used to template it, is that you start with a string of HTML, pull out what you know you want to replace, and put in the data that you want.
I've shown you an ugly, ugly template (it'd be better if I only had to write in an array of variable names, and it did the rest... ...or if it looked through the string to find {{X}} and then looked through an object for the right value to replace what it found).
This also has security holes, if you don't control both the template and the data (if you allow for end-user input anywhere on your site, then you don't have control).
But this should be enough to show how templates do what they do, and why.
i have a paragraph in the database its like
$str ="this is a paragraph i show shortly and when i click on the view more it will show completely for that i am using the ajax and retrieve it "
i show this like
this is a paragraph i show shortly
php for show the first some word is
function chop_string($str, $x)// i called the function
{
$string = strip_tags(stripslashes($string));
return substr($string, 0, strpos(wordwrap($string, $x), "\n"));
}
and when user click on the view more it will display rest of it but the problem it that how to skip this this is a paragraph i show shortly and show the rest of it
i want to show the paragraph after the $x on click on view more
For truncating a string by character of word amount:
This SO question may be of help.
As would this one.
Here's some code that does it specifically by word count.
As far as showing more text on the click of a link goes, what I would suggest is loading the string from the database one time and format it's output. If your string is:
This is whole string pulled from my database.
Then the following code would be formatted like such:
HTML
<p class="truncate">This is the whole string <a class="showMore">Show more...</a><span> pulled from my database.</span></p>
CSS
p.truncate span { display: none; }
That way you can use Javascript (preferably through a library like jQuery which I've chosen for my code below) to hide or show more of your solution without having to make a second database request using AJAX. The following Javascript would do what you're requesting:
$("a.showMore").on("click", function() {
$(this).parent().find("span").contents().unwrap();
$(this).remove();
});
Here's a fiddle to play with!
I have made an example here: shaquin.tk/experiments/showmore.html.
You can view the source to see all of the code behind it. The PHP code is displayed on the page.
If you don't want to display the start string when Show more is clicked, replace the JavaScript function showMore with this:
function showMore() {
if(state == 0) {
state = 1;
document.getElementById('start').style.display = 'none';
document.getElementById('end').style.display = 'block';
document.getElementById('showmore').innerHTML = 'Show less';
document.getElementById('text-content').className = 'expanded';
document.getElementById('start').className = 'expanded';
} else {
state = 0;
document.getElementById('start').style.display = 'block';
document.getElementById('end').style.display = 'none';
document.getElementById('showmore').innerHTML = 'Show more';
document.getElementById('text-content').className = '';
document.getElementById('start').className = '';
}
}
Hope this helps.
Use this function :
function trim_text($string, $word_count)
{
$trimmed = "";
$string = preg_replace("/\040+/"," ", trim($string));
$stringc = explode(" ",$string);
//echo sizeof($stringc);
//echo " words <br /><br />";
if($word_count >= sizeof($stringc))
{
// nothing to do, our string is smaller than the limit.
return $string;
}
elseif($word_count < sizeof($stringc))
{
// trim the string to the word count
for($i=0;$i<$word_count;$i++)
{
$trimmed .= $stringc[$i]." ";
}
if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
return trim($trimmed).'..';
else
return trim($trimmed).'...';
}
}
$wordsBefore = 3;
$numOfWords = 7;
implode(' ', array_slice(explode(' ', $sentence), $wordsBefore, $wordsBefore+$numOfWords));
This will return the first 7 words of a sentence if you save it to a variable named sentence.