I want to limit the size of a paragraph of text. The wrapper div has a dynamically created ID and the paragraph text is also dynamically inserted. The HTML and JavaScript are in the same file.
The HTML
echo"
...
<div id ='subTextWrapper$sub_id' >
<p>$submission_text</p>
</div>
...";
The JavaScript:
echo"
<script>
...
var submissionId = $sub_id;
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0, 50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more' + submissionId).click(function () {
$('#subTextWrapper' + submissionId).html(submissionString);
});
...
</script>";
In the if statement above I want to concatenate the class name read-more with ``` the variable submissionId:
`<a class='read-more' + submissionId>Read more</a>`
This doesn't seem to work. I am not an expert in JS, so any help would be appreciated. Just a note, when I remove the variable submissionId then it works, but obviously it expands all my dynamically created submissions.
You concatenation seems wrong.
What you are currently inserting is exactly what you see as string:
<a class='read-more' + submissionId>Read more</a>
and not the value of submissionId. Since you are not handling the two different delimiters correctly. You have ` enclosing the whole a element and ' enclosing the class. You are closing the class before adding the submissionId and not closing the main literal to acutally include the value of submissionId
.
You can fix it like (if submissionId is a string):
`<a class='read-more` + submissionId.trim() + `'>Read more</a>`
or
`<a class='read-more#Sub.'>Read more</a>`.replace('#Sub.', submissionId.trim())
You could also use an array to build your string to avoid the different delimiters:
//var submissionId = 1234;
var tString = [];
tString.push("<a class='read-more"); //REM: Open the class attribute and not closing it since submissionId is part of the class
tString.push(submissionId); //REM: Adding the value of submissionId
tString.push("'>Read more</a>"); //REM: Closing the class attribute
console.log(tString.join('')); //-> <a class='read-more1234'>Read more</a>
Since submissionId looks like an id/number to me, please be aware that classnames shall not start with digits.
Furthermore if you want to limit the characters of a string you could use String.prototype.substring() instead:
submissionString.substring(0, 50);
would it not work like so.
echo"
<script>
//Limit size of a submission if too long and show a link to read more
var submissionString = $('#subTextWrapper' + submissionId).html();
if (submissionString.split(' ').length > 50) {
$('#subTextWrapper' + submissionId).html(submissionString.split(' ').slice(0,
50).join(' ')
+ ' ... '
+ `<a class='read-more' + submissionId>Read more</a>`);
}
$('a.read-more'$sub_id).click(function () {
$('#subTextWrapper'$sub_id).html(submissionString);
});
...
</script>";
or you could also concatenate like so
$('a.read-more'".$sub_id.")
Related
I'm trying to add an <a> element around a string that currently exists as a Javascript variable.
The resulting element should display as: 'copyright symbol' + 'companyName' + 'this year's date'. BUT with ONLY the variable 'companyName' acting as an html link
Existing JS
const companyName = "ANY BUSINESS NAME";
function setCopyrightText() {
$("#ifcCopyright").html("© " + companyName + " " + new Date().getFullYear());
}
Existing HTML
<span class="textHeavy fontWhite" id="ifcCopyright"></span>
I've tried several approaches and I'm beginning to realise there must be a simpler solution but I'm missing it _ I've been through several answers on Stack but unsuccessful in finding what I need
Thanks in advance for any suggestions
.html() takes A string of HTML to set as the content of each matched element. Did you try this :
const companyName = "ANY BUSINESS NAME";
function setCopyrightText() {
$("#ifcCopyright").html("© <a href='https://www.google.com' target='_blank'>" + companyName + "</a>" + new Date().getFullYear());
}
setCopyrightText();
Codepen
Please put link to your company site where the # is currently placed.
const companyName = "Peuconomia Int'l Pvt. Ltd.";
function setCopyrightText() {
$("#ifcCopyright").html("© " + companyName + " " + new Date().getFullYear().toString());
}
setCopyrightText();
I have a list of elements. However, the length of this list varies between trials. For example, sometimes there are 6 elements and sometimes there are 8. The exact number is detailed in an external metadata.
To display this variable list, I've written:
var html = '';
html += '<div id="button' + ind + '" class="buttons">';
html += '<p>' + name + '</p></div>';
display_element.innerHTML = html;
If I were to 'inspect' the elements in my browser, they would appear to have IDs of button0.buttons, button1.buttons, etc.
Now I am trying to attach event listeners to each element but my code is not working so far. Different forms of broken code below:
document.getElementById("button' + ind + '").addEventListener("click", foo);
$("#button' + ind + '").click(foo);
document.getElementById("button").addEventListener("click", foo);
$("#button").click(foo);
Any help would be very appreciated! Thanks.
You wrong at concat string update it as
document.getElementById("button" + ind).addEventListener("click", foo);
var html = '';
var ind = 1;
var display_element = document.getElementById("test");
html += '<div id="button' + ind + '" class="buttons">';
html += '<p>' + name + '</p></div>';
display_element.innerHTML = html;
document.getElementById("button" + ind).addEventListener("click", foo);
function foo(){
alert('click');
}
<div id="test"></div>
Use "document.getElementsByClassName" get all botton elements then foreach to add click function.
document.getElementsByClassName('buttons').map( element => { element.addEventListener("click", foo) })
To answer the question of why neither of those uses of document.getElementById() are working for you, you are mixing your quotes incorrectly. "button' + ind '" evaluates to exactly that, rather than evaluating to "button0", "button1", etc. To make your code more readable, and to avoid similar quote mixing issues, I would recommend looking into template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
With modern JS if you want to execute the same function you won't require to add an id to each button.
Just use the class added to the buttons like this:
document.querySelectorAll('.buttons').forEach(button => {
button.addEventListener('click',foo);
});
Then use the event parameter in that function to get the target node & execute whatever you want. You can also add data attributes in those buttons to use while executing that function.
I'm currently trying to make an app that tweets out the quote that's currently in the text bubble. However, when I use this line of code,
<a class="twitter-share-button" href="https://twitter.com/intent/tweet?text" + encodeURIComponent(quote.quote + ' - ' + quote.author);>Tweet</a>
It doesn't take me anywhere. Is there any way I could get this working or would I need to use an external Twitter button?
Thanks!
CodePen Link: http://codepen.io/Jelani/full/rOmrOJ/
You can't embed javascript in your markup like that. One approach you could take would be to add some code to your randomQuote function like this:
var randomQuote = function() {
... // current code
var text = quote.quote + ' - ' + quote.author;
$('.twitter-share-button').attr('href', "https://twitter.com/intent/tweet?text="+encodeURIComponent(text));
}
Another approach would be to move your quote variable declaration out of the randomQuote function and set an onclick on the twitter-share-button
<a class="twitter-share-button" onclick="goTweet()">Tweet</a>
that calls a function that does something like:
function goTweet() {
var text = quote.quote + ' - ' + quote.author;
window.location.href = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(text);
}
Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
Which appears like Roster: in the View
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
Which will update my View to Roster: John, Frank, Susan, ect..
However, I am trying to now add <a href> tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
which displays as
Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, ect..
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.. :(
Any help appreciated, Thank you!
Well, solution is quite obvious
Just replace
$("#teamRoster").text(rosterListings);
With:
$("#teamRoster").html(rosterListings);
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html
The problem is that you're using .text(), which will insert only text into the span, as seen here.
You need to use .html() if you want what is inserted to actually render as HTML.
So, try this:
$("#teamRoster").html(rosterListings);
Demo
Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:
if (i !== teamRoster.length - 1) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}
As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.
Here is a jsFiddle showing the difference:
http://jsfiddle.net/89nxt/
$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");
I have seen a similar question, HERE and have tried that, but I can't seem to get it working.
Here is my code for dynamically generating table rows.
for (var contribution = 0; contribution < candidate.contributions.length - 1; contribution++) {
var id = candidate.contributions[contribution].donor_id;
var uid = candidate.contributions[contribution].user_id;
$("#history-table").append(
"<tr onclick='" + parent.viewEngine.pageChange('public-profile', 1, id, uid) + ";>" +
"<td class='img-cell'>" +
"<img class='profile-avatar-small' src='/uploads/profile-pictures/" +
candidate.contributions[contribution].image + "' alt='' /></td><td class=''>" +
"<h2>" + candidate.contributions[contribution].firstname +
" " + candidate.contributions[contribution].lastname + "</h2></a><br/><br/>" +
"<span class='contribution-description'>" + candidate.contributions[contribution].contribution_description + "</span></td>" +
"<td><h3>$" + formatCurrency(candidate.contributions[contribution].contribution_amount) + "</h3></td></tr>");
}
This still executes the click event as soon as the page loads, which is not the desired behavior. I need to be able to click the tr to execute the click event.
Pass the whole thing as a string:
"<tr onclick='parent.viewEngine.pageChange(\'public-profile\', 1, " + id + ", " + uid + ");>" // + (...)
But, as you are using jQuery, you should be attaching the click handler with .on().
(I really don't recommend using inline event handlers like that, especially when you're already using jQuery, but anyway...)
The problem is that you need the name of the function to end up in the string that you are passing to .append(), but you are simply calling the function and appending the result. Try this:
...
"<tr onclick='parent.viewEngine.pageChange(\"public-profile\", 1, " + id + "," + uid + ");'>" +
...
This creates a string that includes the name of the function and the first couple of parameters, but then adds the values of the id and uid variables from the current loop iteration such that the full string includes the appropriately formatted function name and parameters.
Note that the quotation marks around "public-profile" were single quotes but that wouldn't work because you've also used single quotes for your onclick='...', so you should use double-quotes but they need to be escaped because the entire string is in double-quotes.
I'm wondering if you might be better simplifying things a bit.
If your rows are being dynamically added, then try putting some kind of meta-data in the <tr> tag, e.g. something like this:
<tr id="id" name="uid">
Then try the following with your jQuery (v.1.7 required):
$('#history-table tr').on('click', function(){
parent.viewEngine.pageChange('public-profile', 1, this.id, this.name);
});
This will likely require modification depending on how your page rendering works but it's a lot cleaner and easier to read having been removed from your main table markup.
Well that's because you're executing the function, not concatenating it. Try:
onclick='parent.viewEngine.pageChange("public-profile", 1, id, uid);'
Take this ->
$("#contribution-" + uid).click(function(){
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
And do two things:
1) Move it outside of the 'for' statement
As soon as the for statement is executed, the click function will be executed as well. The click function is not being supplied as a callback function in this for statement.
2) Change it to ->
$("tr[id^='contribution-'").on('click', function(){
var idString = $(this).attr("id").split("-"); //split the ID string on every hyphen
var uid = idString[1]; //our UID sits on the otherside of the hyphen, so we use [1] to selec it
//our UID will now be what we need. we also apply our click function to every anchor element that has an id beginning with 'contribution-'. should do the trick.
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
This is my solution.