javascript load image to div onclick - javascript

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;
}

Related

Concatenate javascript string and variable in an echo statement

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.")

Calling a Javascript function with parameters from innerHTML

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 + ');

Single quote, double quote, plus sign in Javascript

I'm not good in JS. I tried to modify a jQuery plugin from these codes:
aTag += " style='"+innerStyle+"'";
aTag += arrow + '<span>text here</span>';
to these codes:
//aTag += " style='"+innerStyle+"'";
aTag += arrow + '<span style="'+innerStyle+'">text here</span>';
Basically I want to move the content of innerStyle from anchor tag to span tag. However, in Firebug I saw this mess after the move:
<span blue;"="" solid="" 1px="" border:="" 25px;="" text-indent:="" transparent;="" -80px="" 5px="" scroll="" no-repeat="" image.png")="" images="" web="" 127.0.0.1="" http:="" style="background: url(">text</span>
Why it works in anchor tag but not in span tag? What's the use of plus (+) signs?
+ does just what it looks like it does in this case (concatenate text). The issue here is that the HTML that is being generated in the first instance looks like this:
style='some contents with a " symbol'
while in the second case what is being generated is this:
style="some contents with a " symbol"
... which, as you can see, is broken - change your code to:
aTag += arrow + "<span style='" + innerStyle + "'>text here</span>";
and it will work.

Why is my jQuery .css function not working?

I'm building some kind of add/remove taglist that is connected with mySQL. I've managed to get the tags from the database to display with a ajax call, but i can't do any kind of operation to them. Not even a common style. When i check with Firebug all the html seems to be in place so i can't figure out what's wrong. Here is my code:
jQuery:
$(document).ready(function() {
$("#ontvangenjson").css("border","3px solid red");
$.getJSON("jason2.php", function(data) {
$.each(data, function(){
var merkTag = " <a class=\"deletemerk\" href="+"http://localhost/website/remove_merk.php?id="+this.pkFavorietemerken+">" + this.merken + "</a>";
$("#ontvangenjson").append(merkTag);
});
});
});
PHP: jason2.php
$merken_lijst = "SELECT favorietemerken.pkFavorietemerken, favorietemerken.merken FROM favorietemerken JOIN bedrijven ON bedrijven.pkBedrijvenID=favorietemerken.fkBedrijvenID WHERE favorietemerken.fkBedrijvenID=$neem_id";
$rows = array();
$sth = mysql_query($merken_lijst);
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
RECEIVED JSON:
[{"pkFavorietemerken":"71","merken":"Nike"},{"pkFavorietemerken":"70","merken":"Le Coq Sportif"},{"pkFavorietemerken":"69","merken":"Converse"},{"pkFavorietemerken":"68","merken":"Champion"},{"pkFavorietemerken":"67","merken":"Adidas"}]
HTML:
<body>
<h1><label for="brands-form-brand">Get JSON data</label> <input type="button" id="knop" value="get JSON" /></h1>
<hr />
<p class="section-title"><strong>JSON Data received</strong></p>
<div id="ontvangenjson"> </div>
</body>
ANSWER
After alot, alot,alot of research I've finaly solved this problem. The code wasn't really wrong but a piece of it was misplaced. The get.JSON is asynchronous meaning if you want to make any changes using the jQuery .css function you will need to do that inside the callback for the getJSON.
$.getJSON("jason2.php", function(data) {
var merkTag = "";
$.each(data, function(){
merkTag += " <a class=\"deletemerk\" href="+"http://localhost/website/remove_merk.php?id="+this.pkFavorietemerken+">" + this.merken + "</a>";
});
$("#ontvangenjson").append(merkTag);
// NEW CODE
$(".deletemerk").css("border","3px solid red");
});
Shorthand properties (such as border) are not supported by jQuery.css().
http://api.jquery.com/css/
If you want to use all the three properties of border, try defining them independently , it might solve your problem.
I'm not sure this will solve your problem, but I would start by trying to clean up the way you're making that link. You may have missed one or two quotes. Instead of the confusion of escaping or failing to escape double quotes, just surround your string with single quotes:
var merkTag = '<a class="deletemerk" href="http://localhost/website/remove_merk.php?id='
+ this.pkFavorietemerken
+ '">'
+ this.merken
+ '</a>';
This leaves you free to use double quotes when you're building an HTML string. I've used multiple lines here just for clarity's sake. Clarity over brevity.

jquery: "Exception thrown and not caught" in IE8, but works in other browsers

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?!

Categories

Resources