Jquery for loop not working - javascript

I am currently working on a site that does not allow me to edit some of the html content on each of the pages because it is part of a template. I am using Jquery to insert the divs on each page so that i can style them for later. I am currently stuck on this piece of code and cannot get it to work for me. Any suggestions would be greatly appreciated.
jQuery(document).ready(function() {
var URLarray = {
"/100.htm", "<div class='Plugins-div'>Volusion Plugins</div>";
"/101.htm", "<div class='Pricing-div'>Pricing</div>";
"/102.htm", "<div class='Services-div'>Services</div>";
"/103.htm", "<div class='Contact-div'>Contact Us</div>";
}
jQuery.each(URLarray, function(key, value) {
if (location.pathname.indexOf(key) > -1) {
pageHTML = URLarray
jQuery('div#navheader').after('<div id="top-banner" class="col-xs-12"><div class="text-center container">' + pageHTML + '</div></div>');
}
}
});
});

Your code doesn't work (and causes an exception, check your console), because it is full of syntax errors. Object literal that looks like and array (and is named as an array), but has semicolons inside, misplaced closing curly braces, assignment of object where a string was probably meant to be used...
It's not entirely clear what you want to do, but this will probably work (and is at least valid code):
var URLarray = {
"/100.htm": "<div class='Plugins-div'>Volusion Plugins</div>",
"/101.htm": "<div class='Pricing-div'>Pricing</div>",
"/102.htm": "<div class='Services-div'>Services</div>",
"/103.htm": "<div class='Contact-div'>Contact Us</div>"
}
jQuery.each(URLarray, function(key, value) {
if (location.pathname.indexOf(key) > -1) {
jQuery('div#navheader').after('<div id="top-banner" class="col-xs-12"><div class="text-center container">' + value + '</div></div>');
}
});

Related

addeventlistener to indexed element

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.

Whats the proper syntax to append a list with multiple classes to jQuery? [duplicate]

This question already has answers here:
How to add items to a unordered list <ul> using jquery
(4 answers)
Closed 6 years ago.
I'm attempting to append a li to a class with multiple classes in the li.
So my HTML code is :
<div class="maincontent">
<ul>
<div class="content">
<div>
</ul>
</div>
And jQuery :
$.getJSON(url, function(data) {
$.each(data, function(n, newData) {
$(".content")
.append("<li class='my-li-class'>")
.append("<div class='imageclass'><img src='"+newData.img+"' class='innerimageclass'></div>")
.append("<div class='another-inner-div'>")
.append("<div class='main-title'>"+newData.title+"</div>")
.append("</div>")
.append("</li>");
});
});
I'm reading the data from the json. The json data is fine. I can show the data correctly if i use only 1 append and add the entire code in it. But the code looks very bad. So i want to break it down to each line to look nice. Im doing something wrong with the append. Please help.
Thanks.
Appending <li> doesn't append an HTML string, it appends a new element, that opens and closes. So your divs aren't inside the list items. Since you have the whole HTML tree, just .append() it all at once:
$.getJSON(url, function(data) {
$.each(data, function(n, newData) {
$(".content").append(
"<li class='my-li-class'>" +
"<div class='imageclass'><img src='"+newData.img+"' class='innerimageclass'></div>" +
"<div class='another-inner-div'>" +
"<div class='main-title'>"+newData.title+"</div>" +
"</div>" +
"</li>");
});
});
When we append an element, it get added to DOM tree so if we check your code,
$.getJSON(url, function(data) {
$.each(data, function(n, newData) {
$(".content")
.append("<li class='my-li-class'>")
.append("<div class='imageclass'><img src='"+newData.img+"' class='innerimageclass'></div>")
....
});
});
The time you did
$(".content")
.append("<li class='my-li-class'>")
HTML got changed to
<div class="content">
<li class='my-li-class'></li>
<div>
Next append won't be happening inside li
There are multiple ways you can do it,
Create a variable and append it to div.content.
var htmlData = "<li class='my-li-class'>" +
"<div class='imageclass'><img src='"+newData.img+"' class='innerimageclass'></div>" +
"<div class='another-inner-div'>" +
"<div class='main-title'>"+newData.title+"</div>" +
"</div>" +
"</li>");
Or if you really want to make it really clean, use createElement and related function to created each element individually and finally add it to div.content.
Please note: It is significantly faster to append multiple items as a single string, than to append multiple items one at a time. You need to rework your code to create a single HTML string and append once at the end.
e.g.
$.getJSON(url, function(data) {
var html = "";
$.each(data, function(n, newData) {
html +=
"<li class='my-li-class'>" +
"<div class='imageclass'><img src='"+newData.img+"' class='innerimageclass'></div>" +
"<div class='another-inner-div'>" +
"<div class='main-title'>"+newData.title+"</div>" +
"</div>" +
"</li>");
});
$(".content").append(html);
});
or use .html()
$(".content").html(html);
As noted in comment, a DIV is not a valid child of a UL, so you need to target the UL instead:
$(".content").parent().append(html);
Or add a class to the UL instead and target that directly.

Value not passing properly in javascript function while iterator using $.each() function

I am returning array of object called "categories" from the Ajax call and then i am replacing its object(category) value in the string(categoriesList). Then i am replacing this string in the html div Area as $("#divAreaName").html("StringName");
For proper understanding the code is shown below:
$.each(categories,function(index,category){
categoriesList = categoriesList +
"<div class='media'>"+
"<img onclick=dispProductCategoryWise('"+category.name+"','"+category.id+"','"+id+"','"+retailerId+"'); src='${pageContext.request.contextPath}"+category.image+"'>"+
"</div>"+
"<div class='item-info'>"+
"<div class='item-name item-row'>"+
"<span class='full-item-name'>"+category.name+"</span>"+
"</div>"+
"</div>";
});
Then i am replacing the string in the div area using the following line of code
$("#divName").html(categoriesList);
However the problem is when category.name is "Fruits and Vegetable". The HTML is formed as shown below:
<img onclick="dispProductCategoryWise('Fruits" &="" Vegetable','60','1','2');="" src="/closerby/images/customer/category/FandV.jpeg">
Can someone let me know why the values are not getting passed properly and the possible solution?
Interesting problem, it seems the spaces are strangely converted when using .html(). As if the '/" itself are rendered. console.log gives correct string as well.
As an alternative, create an event on that specific image using a dynamically generated id.
Like so:
categories = {
"category":{
"name": "Fruits and Vegetables",
"id": 1,
}
}
$.each(categories,function(index,category){
categoriesList =
"<div class='media'>"+
"<img id='specific_"+index+"' src='{somethingwashere}'>"+
"</div>"+
"<div class='item-info'>"+
"<div class='item-name item-row'>"+
"<span class='full-item-name'>"+category.name+"</span>"+
"</div>"+
"</div>";
$("#myDiv").html(categoriesList);
//Added event.
$('#specific_'+index).click(function() {
return displayProductCategoryWise(category.name, category.id);
});
});
function displayProductCategoryWise(name, id) {
alert(name);
alert(id);
}
Ive only used $('selector').each(fn) to do something for each matched jquery element
Perhaps try using categories.forEach(function(category, index){ ...
Are you turning the quote makes into special characters..... add a blackslash ()
Something like :
<img onclick=dispProductCategoryWise('\"+category.name+\"','\"+category.id+\"','\"+id+\"','\"+retailerId+\"'); src='${pageContext.request.contextPath}\"+category.image+\"'>\"

Bookmarklet Javascript Array Leak?

For my project, I am creating a bookmarklet which gives users tag options. I am passing an array in of the user's top tags and looping in javascript to generate all the options.
The problem is that the array is picking up rogue functions from the underlying page that are somehow making it into the array and as you can see in the image below: screwing up everything.
I've tried manually removing these by taking off the blocks by string length - but I discovered that in some cases (as in the case of wired magazine articles) the rogue functions has an open script tag which I am removing and thus breaking the bookmarklet.
Here is the code where I build the javascript array:
<?php foreach ($default_aspects as $aspect_id => $aspect_display) { ?>
default_aspects['<?php echo $aspect_id; ?>'] = '<?php echo $aspect_display; ?>';
<?php } ?>
And here is the code where I print the array out:
html += '<div id="bml_category___" style="display:none; opacity:0;">';
for (var i in default_aspects) {
html += '<div class="bml_category_block___">' + default_aspects[i] + '</div>';
};
You can see what this looks like (and the problem) here:
http://cl.ly/0W1Y0B0U1S210L1h2y2n
I guess there is some sort of leak?
That page is probably using a JavaScript framework, which modifies native objects. Use the hasOwnProperty method to filter out these methods.
I use Object.hasOwnProperty.call(default_aspects, i) instead of default_aspects.hasOwnProperty(i), to make sure that a property named hasOwnProperty does not break your code.
html += '<div id="bml_category___" style="display:none; opacity:0;">';
for (var i in default_aspects) {
if (Object.hasOwnProperty.call(default_aspects, i)) {
html += '<div class="bml_category_block___">' + default_aspects[i] + '</div>';
}
};
If you've got a modern browser, it's easier to use Object.keys():
var keys = Object.keys(default_aspects);
for (var i=0; i<keys.length; i++) {
html += '<div class="bml_category_block___">' + default_aspects[i] + '</div>'
}
Or, using Array.forEach:
Object.keys(default_aspects).forEach(function(key) {
html += '<div class="bml_category_block___">' + default_aspects[key] + '</div>'
});

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