How add a link in only one existing li - javascript

This is my problem: I have a ul list that has undertemined number of li, because it depends the number of the files in a folder. It lists those files in a div, and when the mouse hovers one of them, I want it till get the new link only in its div.
My code is this:
function showImages(data) {
var ul = "<ul id='productImages'>";
for (i = 0; i < data.length; i++) {
var tempButton = i;
var link = '#Html.ActionLink("Pedir Detalhes","ContactUs", new { tempVerifyButton = 3}, new { #class = "visualize"})';
var directories = data[i];
ul += "<li id = 'element" + i.toString() + "'><img src='../Content/images/Products/" + directories.ImageName + "' /><div class = 'description'><div id = 'productsText'>" + directories.DescriptionName + "</div></div></li>";
}
ul += "</ul>";
$("#directoryImages").append(ul);
for (i = 0; i < data.length; i++) {
var element = "ul#productImages li#element" + i.toString();
$(element).hover(
function () {
var link = '#Html.ActionLink("Pedir Detalhes","ContactUs", new { tempVerifyButton = 3 }, new { #class = "visualize"})';
$(".description").append("<div class = 'visualize'>" + link + "</div>");
});
}
}
The problem with this code is when the mouse hovers one of the li element, all .description gets the link, and I want only the current hovered li till get the link, and then when it loses focus the link disappears.
EDITED:
I already use $(this).append($(".description").append("< div class = 'visualize'>" + link + "< /div>"));
Any ideas?

Try with this(current element)
$(this).append("<div class = 'visualize'>" + link + "</div>");
http://learn.jquery.com/javascript-101/this-keyword/
this is a special keyword that is used in methods to refer to the object on which a method is being invoked.

Related

How to return to the starting position in a dynamically rebuilt table after having followed a link from it?

I rebuild a table (tbody) from the local storage. When it is necessary, I rebuild the <a> tag to get a link to an image. Contrary to what happen normally, when returning from the linked document or image to the calling document containing the rebuilt table, the cursor position nor the scrollbar position is retained, and the table is re-positioned at the beginning (row 0, col 0). I would like that the user would not have to scroll again to find it starting position (with the link) in the table.
The problem is simple to explain and I already did it. By clicking to expand a small view of a table in order to get a full view of it on a new page, I have to dynamically rebuild this table from information in the localstorage: firstly call the function storeLocOeuvresTbl() in the origin page; secondly, the function getInventOeuvresTblFromStoreLoc() in the destination page. This can be done by clicking on the link according to the code here : Le contenu de cette table peut être trié en cliquant sur les entêtes de colonnes.
Veuillez suivre ce lien
Expand
pour agrandir la table sur une page séparée..
If I follow a link from a cell in the built table in the destination page and return to this page from any other document/page accessed through this link, the cursor and scrollbar positions are lost. I suppose having to specify some property/attribute.
Which property/attribute do I have to specify for a dynamically built table so that the table from which I followed the link, does not move to the initial pos (0,0) when I return from this link. If I have to specify a property to keep the position, at which level? Div, table contained in the div, tbody?
Whit a dynamically built table, the normal behavior is perturbed.
Here is a link to a test page simplifying this problem:
http://www.danielpisters.be/testTable.html
Click bellow the table and you get a full view of the table in
http://www.danielpisters.be/testExpandTestTable.html
Move right to the column header "tLink" (all the others are "Foo", "Bar"). Then move down in the column until you reach a cell with a link. Click on it and you will see an image on another page. Returning from it, the position on the cell containing the link is lost, becoming 0,0.
// Build the table from the origin document
<script type="text/javascript">
function storeLocOeuvresTbl()
{
var oTable = document.getElementById('myOeuvresTable');
var s = "";
var stopAlert = true;
if (oTable == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
var aTBODY = oTable.getElementsByTagName("tbody");
localStorage.setItem("myOeuvresTableTBlen", aTBODY.length);
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var aTR = aTBODY[i].getElementsByTagName("tr");
localStorage.setItem("myOeuvresTableTB" + i + "len", aTR.length);
for (var j = 0; j < aTR.length; j++)
{
var aTD = aTR[j].getElementsByTagName("td");
localStorage.setItem("myOeuvresTableTB" + i + "TR" + j + "len", aTD.length);
var aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTD.length; k++)
{
s = s + aTD[k].id + ": " + aTD[k].innerHTML + "|";
var tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
var innerHTML = "";
if (aTD[k].innerHTML.length > 0)
{
innerHTML = aTD[k].innerHTML;
}
else
{
innerHTML = " ";
}
localStorage.setItem(tdId, innerHTML);
innerHTML = localStorage.getItem(tdId);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
alert("innerHTML get: " + innerHTML);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
}
s = s + "\n";
}
}
return s;
}
// Rebuild onLoad of the destination document
<script type="text/javascript">
function getInventOeuvresTblFromStoreLoc()
{
var tbl = document.getElementById('myOeuvresTable');
var s = "";
var tdId = "";
var innerHTML = "";
var aTBODYlen = 0;
var aTRlen = 0;
var aTDlen = 0;
var stopAlert = true;
var arrEvent = new Array("onMouseOver", "onMouseOut", "onClick", "onDbleClick", "onMouseUp", "onMouseDown", "onFocus", "onBlur");
var DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
if (tbl == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
aTBODYlen = parseInt(localStorage.getItem("myOeuvresTableTBlen"));
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODYlen; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var tblBody = tbl.tBodies.item(i);
aTRlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "len"));
for (var j = 0; j < aTRlen; j++)
{
var row = document.createElement("tr");
aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTDlen; k++)
{
var cell = document.createElement("td");
tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
innerHTML = localStorage.getItem(tdId);
if (innerHTML.substr(0, 7).toLowerCase() == "<a href")
{
var link = document.createElement("a");
var indDblQuote1 = innerHTML.indexOf('"');
var indDblQuote2 = innerHTML.indexOf('"', indDblQuote1 + 1);
var indOf1 = innerHTML.indexOf(">");
var indOf2 = innerHTML.toLowerCase().indexOf("</a>");
var cellLink = innerHTML.substring(indDblQuote1 + 1, indDblQuote2);
var cellText = innerHTML.substring(indOf1 + 1, indOf2);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
var s = "innetHTML: " + innerHTML + "; " + "cellLink: " + cellLink + "; " + "cellText: " + cellText;
alert(s);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
link.setAttribute('href', cellLink);
link.appendChild(document.createTextNode(cellText));
cell.appendChild(link);
}
else
{
var cellText = document.createTextNode(innerHTML);
cell.appendChild(cellText);
}
row.appendChild(cell);
s = s + tdId + ": " + innerHTML + "|";
}
tblBody.appendChild(row);
s = s + "\n";
}
tbl.appendChild(tblBody);
}
return s;
}
</script>

Changing the CSS style for multiple check boxes not working

I have an application using firebase which looks like this:
The tick boxes to the right hand side of each 'Book', when clicked, sends the value of the firebase object into a string as shown below:
When clicking these tick boxes, I would like the style of the box and content to change so they turn blue. I have added this piece of code into the on click event:
function select(data, book, key) {
//What I added
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
//
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
However, this only turns the first box blue. No matter which check box I click, the first one just changes to blue and the rest stay grey.
Here is the JS code which creates the checkbox icons and the JS to highlight the selected check boxes.
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
//This generates the 3 columns on the application page
for (var i = 0; i < 10 && i < list.length; i++) {
lis += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 10; i < 20 && i < list.length; i++) {
lis2 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
for (var i = 20; i < 30 && i < list.length; i++) {
lis3 += '<li style="width: 150px" data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
};
//This creates the 3 icons of delete, clear and select.
function genLinks(key, bkName) {
var links = '';
links += '<i id="deleteBook" class="material-icons">delete</i> ';
links += '<i id="removeBook" class="material-icons">clear</i> ';
links += '<i id="selectBook" onclick="functionSelected()" class="material-icons">check</i>';
return links;
};
function del(key, bkName) {
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
//This is the function to select and insert the data into the string as well as highlight each checkbox
function select(data, book, key) {
document.getElementById('selectBook').style.color="blue";
document.getElementById('selectBook').style.borderColor="blue";
var selectBookRef = book;
document.getElementById('alltext').value += selectBookRef + ',';
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
refreshUI(list);
});
If anybody can help it will be much appreciated.
Thanks,
G
The only thing I can see is that you are using the same id tags for multiple different objects on the same page. If you use it at more than one place, use a class! You should never have more than one of the same id because you will be facing a lot of repeating problems..

jQuery click event with parameter not working

I need some help. I am trying to iterate through some Json items, create some li's with some information from the items, but also attach click handlers for the li's, but with a value transmited as parameter.
The problem is that the last value of that parameter is set for or the li's in the list. From what i searched i understood that it has something to do with javascript closure, but can't seem to understand how to fix it.
I am using jQuery and here is the code:
for (var i = 0; i < items.length; i++)
{
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(li).click(function() {
displayPopUp(id);
});
ul.append(li);
}
Could anyone please help me fix this code?
Best regards, Marius.
The issue is that JS is function scoped so the id within your closure is the last id from your for loop. To fix this use forEach so you run each iteration of your loop in a separate scope e.g.
items.forEach(function (el, i) {
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(li).click(function() {
displayPopUp(id);
});
ul.append(li);
});
you need delegated event as elements are created dynamically, you can use class that is being added on li which is video-single:
$(document).on('click','.video-single',function() {
displayPopUp(id);
});
you can read about Delegated Events HERE
in order to bind an event to a dynamically added element you need to delegate it as below:
for (var i = 0; i < items.length; i++)
{
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(document).bind('click',li,function() {
displayPopUp(id);
});
ul.append(li);
}

JS Adding Row to Table With Link Clicked

EDIT: I got it working! It turned out that I had written innerHtml instead of innerHTML. I This topic can be closed.
I am trying to use JS to put the link most recently clicked by a userinto a table row where a row is created each time a link is clicked. The list of links shown is also generated using JS.
The problem I am having is that when I click a link, the table is created with an empty row.
Here is the JS.
function processLinks()
{
var linksList = document.links; // get the document's links
var contents = "";
for ( var i = 0; i < linksList.length; ++i )
{
var currentLink = linksList[ i ];
contents += "<p style =\"background-color:red\"><a href='" + currentLink.href + "'
target='_blank' id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
}
// if user click link var currentLink = linksList[ index of link user clicked ];
//create table
//document.getElementById("link + index to specify element 0,1,2,3, etc for
//id").onclick
document.getElementById( "links" ).innerHTML = contents;
} // end function processLinks
function insertLink(e)
{
var linksList = document.links; // get the document's links
var contents = "";
for (var i = 0; i < linksList.length; ++i)
{
if(document.getElementById("link" + i) )
{
var currentLink = linksList[i];
contents += "<p><a href='" + currentLink.href + "' target='_blank'
id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
tbody = document.getElementById("tableBody");
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.innerHtml = contents;
row.appendChild(cell);
tbody.appendChild(row);
}
}
document.getElementById("tableBody").onclick = function(){insertLink()};
}
document.addEventListener("click", insertLink, false);
window.addEventListener( "load", processLinks, false );

style last item in list of feed entries (google feed api)

I am using the Google Feed API to pull four items from an RSS feed. I want to style the last item on the list (the fourth) differently from the first three. It seems like there must be a simple way--but I can't seem to figure it out. Here's what I've got:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://the-url-of-my-feed");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("joes-teaser");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var li = document.createElement("li");
li.innerHTML = '<a href="' + entry.link + '" target="_blank">'
+ entry.title + '<span>More »</span></a>';
container.appendChild(li);
}
}
});
}
google.setOnLoadCallback(initialize);
That gives me a nice list of four li items, but I want the last, and only the last, to have a css id of something else--maybe joes-teaser-last or whatever.
In your loop you can check if i is the last one by comparing it to the entries' length.
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var li = document.createElement("li");
if (i == result.feed.entries.length - 1) {
li.className = "lastLi";
}
li.innerHTML = '' + entry.title + '<span>More »</span>';
container.appendChild(li);
}

Categories

Resources