I'm writing html in Javascript using innerHTML, in one case, I'm appending a href tag like so :
txt.innerHTML += 'Read more';
where url is a string containing a url.
And the goToUrl function looks like as follows :
function goToUrl(urlToBrowse) {
window.open(urlToBrowse, "_blank");
}
But my onclick never gets called, can anyone see the problem? Cheers
try this
txt.innerHTML += "<a href='' id='rssLinks' onclick='alert(\"" + url + "\");'>Read more</a>";
//........................................................^............^
//.............................................................may needed
because call would look like goToUrl(http://google.com)
and that's a string so it has to be goToUrl("http://google.com")
EDIT 01/2020 - "New" way to add this parameter
Since ES6, you can write it with a Template-String
txt.innerHTML += `<a href='' id='rssLinks' onclick='goToUrl("${url}");'>Read more</a>`
Change to this:
onclick="goToUrl(' + url + '); return false;"
That will prevent the action of the browser.
You need to append onclick to your element txt.onclick="goToUrl(' + url + ');
Related
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.")
I am trying to come up with code that would create an href tag with a JavaScript functions which gets parameters. Parameters are a string and an object converted into a json string.
My attempt was something like this:
return '<a style="text-decoration:underline;cursor:pointer" target="_blank"' +
' href="javascript:goToStateNewWindow(\'trending\', \'' + JSON.stringify(params) + '\')">' + value + '</a>';
The error was:
Uncaught SyntaxError: Invalid or unexpected token
In Inspect window it looked like this:
<a style="text-decoration:underline;cursor:pointer" target="_blank" href="javascript:goToStateNewWindow('trending', '{" projectid":2313,"alarmsonly":"true"}')"="">test</a>
Can someone please explain what I am doing wrong?
Firstly, it shouldn't be an <a> element, but a <button>. You can use CSS to make it look like <a> if you want.
Secondly, you should rather create en element using document.createElement(), add the attributes and specify a click event listener using the addEventListener() method.
const element = document.createElement('button')
element.setAttribute('type', 'button')
element.setAttribute('style', 'text-decoration:underline;cursor:pointer;')
element.setAttribute('target', '_blank')
element.addEventListener('click', event => goToStateNewWindow('trending', params))
element.innerHTML = value
return element.outerHTML
Can someone please explain what I am doing wrong?
Sorry. But everything. Here's how you should create the element, e.g. in a function.
var a = document.createElement('a');
var t = document.createTextNode(value);
a.appendChild(t);
a.style.textDecoration = 'underline';
a.style.cursor = 'pointer';
a.setAttribute("target", "_blank");
document.body.appendChild(a); // or any other element you want the a to appear in
a.addEventListener("click", function(e) {
e.preventDefault();
goToStateNewWindow('trending', params);
});
Note that you could also style the element with css before...
I want to explain why it doesn't work. It's because in your html you have href="javascript:... when you call JSON.stringify(params) it returns {"projectid":2313,"alarmsonly":true} then the javascript parser stops at the first double quote after href=" ({") and the rest (projectid":2313,"alarmsonly":true}...) become invalid javascript.
I made a function who replace double quotes with single quotes and that worked. May not work if the object have a string value with double quotes.
function goToStateNewWindow(route, body){
console.log('Route: ', route);
console.log('Params: ', body);
}
function doublequotetosingle(obj) {
return JSON.stringify(obj).replace(/"/g, "'");;
}
function test(params, value) {
return '<a style="text-decoration:underline;cursor:pointer" target="_blank"' +
' href="javascript:goToStateNewWindow(\'trending\',' + doublequotetosingle(params) + ')">' + value + '</a>';
}
document.body.insertAdjacentHTML('beforeend', test({ projectid: 2313, alarmsonly: true }, 'test'));
I am using onclick event to perform some acction, but for som reason the second ID is not being passed what am I doing wrong here:
row += '<td>' + data[staff].Naame + '(' + data[staff].place1 + 'fID="' + data[staff].id+ '"' +')</td>'
$(document).on("click", ".name", function (e) {
var code = ($(this).attr("code"))
var fID = ($(this).attr("fID"))
function(code, fID);
});
For some reason fID is not being passed from 'fID="' + data[staff].id+ '"' to function(code, fID); why is that?
Avoid using loads of string concatenation in jQuery, to create elements, as it is generally unreadable and leads to typing mistakes (like not putting the fId inside the tag attributes):
Instead build the element with jQuery. I am not 100% sure of what your link should look like from the code, but something like this (tweak to suit):
var $td = $('<td>').html(data[staff].Naame);
$td.append($('<a>', {class: 'name', code: data[staff].place, fId: data[staff].id}).html(data[staff].place1));
row.append($td);
I think you need to define fID within the <a ... > tag - like you are doing for code.
ie:
...
Try this.
row += '<td>' + data[staff].Naame + ''+data[staff].place1+'</td>'
I want to display image user click from image link in a for loop to a div.
my for loop is as follows.
<a href='' name=my_image[i]
onclick='disp_image('link_image_url')'id=my_image[i] class='popup-open'><img src=my_image[i] width='80' height='65'></a>;
and my javascript function
<script language=\"javascript\">
function disp_image(url){
document.getElementById('image').innerHTML ="<img src=url width='100' height='105'>";
;}
</script>
</script>
However it is not being load in my div content
<div id="image"></div>
can someone has an idea how can i display selected image in a div content dynamically
Use this:
var _leng = my_image.length
, td = "<td><a href='#url#' onclick='displaying(/image#url#)' id='/image#url#'><img src='#url#' width='80' height='65' /></a></td></tr><tr>"
, i;
for (i=0; i < _leng; i++) {
str += td.replace(/#url#/g, my_image[i])
}
Check this example:
http://jsfiddle.net/hMfRG/
You have mismatched quotes so the string isn't being generated properly, or at all... you probably have errors in the console.
str += "<td><a href='" + my_image[i] + " onclick='displaying()' id='/image" + my_image[i] + "'><img src='" + my_image[i] + "' width='80' height='65' /></a></td></tr><tr>";
You can't use these special quotes ‘’ or ”, only use these single or double quotes ' or ".
Example:
document.getElementById('image')
You have displaying() in the loop but below, its called displayImage(). Also, the function expects an argument which you're not supplying in the call.
Look at the syntax highlighting of your post. You can clearly see that your quotes are all over the place. For instance, you have src='"+url+'", which is wrong. You also have "smart quotes" in places. Fix the quotes and it should stop throwing syntax errors.
But most importantly, your onclick function calls displaying(), whereas the function is called displayImage and takes an argument.
I've done it this way:
<div id="result" style="width:450px;height:296px;">
<img name="main" src="/images/image.jpg" alt="">
</div>
function change_pic(img_name,img_src)
{
document[img_name].src=img_src;
}
My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!