Appending a div containing an image in a function - javascript

Everything comes just to the following single line of code, which I probably mess up somewhere and after an hour with something of searching for error I still don't find it, so that's why I'm turning up to you.
$("red").append("<div class = "reddot" style = "top: '+ y + 'px; left: '+ x +'px;"><img src='red.png' height='10' width='10'></div>");
When .append(); is without an argument everything with the syntax is good. After I put what you see in, pops up a message "Uncaught SyntaxError: missing ) after argument list" which I can't find. Please help me to find the mysterious bracket or to fix my syntax or to write this in another way if you think this one won't ever work for me. Sorry for this dump question, I searched a lot for this but it was nowhere said about implementing two or more html tags within an append method.
P.S. The idea is to load a container holding an image by generated elsewhere coordinates.

$("red").append("<div class=\"reddot\" style=\"top: "+ y + "px; left: "+ x +"px;\"><img src='red.png' height='10' width='10'></div>");
All the " should be escaped when in a string with " otherwise JS will assume the string has ended

Try this one
$("red").append("<div class = 'reddot' style = 'top: "+ y + "px; left: "+ x +"px;'><img src='red.png' height='10' width='10'></div>");

Related

Trying to use nested if statements inside forEach loop on javascript array

I am trying to use an if statement inside of another if statement and I simply can't figure out how to get the second if statement to work. The second if statement applies all style changes to the first element (school) in the array. I would like the second if statement to apply the correct styling to all items in the array based on the json data ([school.status]).
I've tried switching to a for statement, tried moving the if statements around and nesting them differently, tried async and moving different parts of the formulas in and out of the code blocks. I've tried running a second forEach statement after the append but I couldn't get that to work either. I think I lack an understanding of how this process works, beyond just the code part, but more the logical operator, and after hours of searching for a straight forward answer, and it being almost 4AM, I figured I would just ask here.
schools.forEach(function(school, index) {
dashboardItemStatus = $(".dashboard-item-status");
if (App.hasClass("mainDash")) {
App.append(
'<div class="dashboard-item"><h5 class="mb-1">' +
[school.name] +
"</h5>" +
'<p style="margin-bottom: -2px">' +
[school.address.street] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.address.city] +
"," +
" " +
[school.address.state] +
" " +
[school.address.zip] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.phone] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.principal] +
"</p>" +
'<p style="margin-top: 8px;background-color: #FFF;padding: 8px 14px;border-radius: 5px;" class="dashboard-item-status" id="dashboardItemStatus">' +
[school.status] +
"</p>" +
"</div>"
);
}
if (school.status == "Normal Operation") {
dashboardItemStatus.addClass("dashboard-item-status-normal");
} else if (school.status == "Full Change") {
dashboardItemStatus.addClass("dashboard-item-status-change");
}
});
So, I suppose the expected results are anytime one of the statuses is "Full Change" the dashboard-item-status-change class is applied, and the dashboard-item-status-normal class is applied to any status that has "Normal Operation". That data is an array that is coming from a json file. That part works just fine. The forEach function works fine and the information displays correctly on the screen. Now though, I need to be able to affect the elements that show the status individually based on the status itself. Right now, as stated above, no matter what status I attempt to affect, the channges all occur on the first element in the array, which I guess makes sense, but I have no idea how to fix it. If I console.log() the names and statuses of the schools inside the second if statement, they display correctly so I know I can find the right values, I just don't know how to affect them. Maybe map or something may work but I honestly don't know how to use that correctly. Any help is really appreciated.

jQuery after() seems to have a race condition

I have a very strange bug, what appears to be a race condition makes a width(); call give different results.
I have this jQuery after call:
this.after(
"<div class='menuItemContainer'>" +
"<div class='menuItemTitle'>" +
$("option:selected", this).text() + "<span class='menuItemDownArrow'>▼</span>" +
"</div>" +
"<div class='menuItemList'>" +
selectionMarkup +
"</div>" +
"</div>"
);
In which I insert html into the DOM.
Next I need to know the combined widths of an element with the class menuItemColums and make their parent div that width.
This markup exists in the variable selectionMarkup.
To do this I do the following:
var w = 0;
$(".menuItemColumn").each(function(){
w += $(this).width();
console.log($(this));
console.log(w);
});
$(".menuItemList").css({
width: w}
);
This works exactly as expected around 70% of the times, but sometimes I get the wrong measure for some of the elements, or at least for sure the first one sometimes is wrong.
The weird part is that the object seem to be correct, and it's properties are the correct width, but the given widht() which is assigned to w is incorrect:
That image, just to clarify shows the result of logging w and the $(this) which should be the same, since $(this)'s width property seems to be the correct one.
I kept debugging and found out two things that lead be to believe that this is race condition:
If I execute the last piece of code I posted you again, when the bug is reproduced, it fixes the problem.
If I do the following calls, the give me different results, one incorrect and the other one (second one) correct:
console.log($(".menuItemColumn:first").width());
setTimeout(function(){console.log($(".menuItemColumn:first").width());},3000);
I was under the impression that the second part of the code will not execute until the first one is finished, what gives here?
Note: I'm not 100% sure that race condition is the word I was looking for, but still, the idea is that.
UPDATE:
As #WereWolf-TheAlpha the output of the console doesn't seem like jquery objects, I now can't reproduce that and I'm only getting this:
Without changing any code.
The issue here is that the Chrome inspector will provide a reference to an object while the object is collapsed in the inspector. When you click that arrow to expand the object, its attributes become real. You can run this to see it occur:
var obj = {};
for (i=0; i<100; i++)
obj['foo'+i] = i;
console.log(obj);
for (i=0; i<100; i++)
obj['foo'+i] = 'gotcha';
console.log(obj);
Now, expand the first object in your inspector. Gotcha!

executing javascript inside href attribute of anchor tag

I checked a lot on Hrefs but couldn't get something related.
I am trying to do this in code behind which is actually a custom control class
writer.Write("<a href='javascript:document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
now this gets me something like this on hover of above anchor 'document.location.href?Test one=2013' and when i click it, this throws an obvious javascript error 'SyntaxError: missing : in conditional expression' because it takes it as a conditional operator and hence finds : missing.
I simply want that document.location.href (current url) should be calculated and the value put in where i use it.
I know that i may simply call a javascript function and inside that function i set the href but can i do it this way?
Try this:
writer.Write("<a href='javascript:window.location = document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
Note that you might have to escape values as needed otherwise JavaScript will become invalid. To prove that above approach works, you can copy-paste following simpler example in any HTML page and see it working:
bla

vb.net window.open

sb.Append("<script language='javascript'>")
sb.Append("window.open('updateRT.aspx?batchno=" + batchno + "&prodcode=" + prodcode + "&maxrunningtime=" + temprunningtime + ",")
sb.Append("top=0, left=0, width=500, height=500, menubar=yes,toolbar=yes,status=1,resizable=yes');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), "abc", sb.ToString())
hi everyone ...above is my vb.net code that i am trying to pass the value to other page and at the same time resize the window that will appear ...
i am not sure why and which error that i encounter and the size od windows still remain the same which is full screen rather than with width = 500 and height=500
can anyone help me out here?
thank you so much and have a nice day ...
:D
Whoops, had misread your code.
You're supposed to pass in the window specification as the third parameter to window.open - check out http://www.w3schools.com/jsref/met_win_open.asp. Right now, you're passing everything in one parameter, since the comma which is intended to close the first parameter is actually part of a string. Try
sb.Append("window.open('updateRT.aspx?batchno=" + batchno + "&prodcode=" + prodcode + "&maxrunningtime=" + temprunningtime + "', '_blank',")
sb.Append("'top=0, left=0, width=500, height=500, menubar=yes,toolbar=yes,status=1,resizable=yes');")

Delimiting four nested items in Javascript/Html

Okay this is frustrating me to no end. I recently coded a page in JS for a buddy of mine who wants to display wedding pictures to a family to see which ones they'd like to purchase.
I used a for loop to count 1-904:
for (beginnum=1;beginnum<=904;beginnum++) { yada yada...
Then, I used adobe bridge to rename the camera files to be 1-904 and their thumbnails (1-904 + _thumb) and used the loop number to display 904 image spaces, and the correctly numbered picture:
[note:using <) in place of the usual open tag since the site wont display it]
IE...
document.write(beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' />");
Opera...
document.write("<div>" + beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' /></div>")
This all works perfectly in IE and Opera (with external CSS modifying the div to not line break).
I then created a function to call up the large version of the picture when clicked on.
The problem is, when I try and nest this function into the JavaScript generated HTML I would need four delimiters. I've heard ''' or """ or the &+numeric; work in some cases as a third and fourth but I can't seem to get them to work... where I run into a problem is here...
[note:again using <) for open tag]
document.write("<a href='javascript:void(0); onClick=
Since I've already used up " and ' I now have nothing left to use to call the function when a picture is clicked.
I usually don't ask for any help, but this time I can't think of anything else that should work... I assume maybe using JS to generate the HTML leaves me with ONLY 2 delimiters that will be recognized by the browser but I am not sure, anyone know for sure? Any fixes anyone can think of?
Thanks,
~Z~
Maybe this will work
for (i=0; i<904;i++)
{
document.write("<div class=\"DivClassName\"><img src=\"pictures_" + i + "thumb.jpg\" onclick=\"OpenAWindowAndDisplayTheBigPhoto(" + i + ")\"></div>");
}
Another approach: Suppose you put everything inside a <DIV id="mainDIV">
var mainDIV = document.getElementByID("mainDIV");
var div, img, a;
for (i=0; i<904; i++)
{
div = document.createElement("DIV");
div.className = "DivClassName";
a = document.createElement("A");
a.href = "javascript:void(0)";
a.onclick = function() {OpenAWindowAndDisplayTheBigPhoto(i);};
img = document.createElement("IMG");
img.src = "pictures_" + i + "thumb.jpg";
mainDIV.appendChild(div);
div.appendChild(a);
a.appendChild(img);
};
Try building the string one piece at a time instead of trying to build the whole literal for the document.write.
Whenever things get too convoluted to follow, just do one part at a time.
var s;
s = "'Hello.' ";
s += '"I must be going."';
Without seeing code it is hard to say for a fact, but you may want to take more advantage of the fact that javascript is a first-class language, so you can create functions and pass them as arguments to other functions, or have functions return functions.
By doing this, you can decompose your page into something that sounds a bit more manageable.
Also, take advantage of the onclick event.
You should be able to simplify the javascript and so avoid this problem, IMO.

Categories