Javascript - Jquery on the fly id retrieving - javascript

I've made a JS utility with jQuery that gives IDs to div elements and to links, which are coordinated.
Example:
div id="container"
div id="1"
div id="2"
div id="links"
a name="1"
a name="2"
So once the page is loaded, when I click on the first link (name="1") it is supposed to show the first div (id="1").
But it seems that as my IDs are created on the fly, the function doesn't seem to find the right div.
Here's my function:
$("#video_grid .grid_item a").each(
function(i) {
/* FINDING 'A' AND GIVING THEM NAME */
$(this).addClass("item" + (i + 1));
$(this).attr("name", "#" + (i + 1));
/* BACKGROUND */
$(this).css("background-image",
"url(images/visu_" + (i + 1) + ".jpg");
$(this).hover(
function() {
$(this).css("background-image",
"url(images/visu_hover_" + (i + 1) + ".jpg")
},
function() {
$(this).css("background-image",
"url(images/visu_" + (i + 1) + ".jpg");
});
});
/* FINDING DIV GIVING THEM IDS */
$("#capsule_player > div").each(function(i) {
$(this).addClass("item#" + (i + 1));
});
/* HERE'S THE PROBLEM */
$("#capsule_player div:first-child").css("display", "block");
/* appel la div correspondante avec la video */
$(".grid_item a").live("click", function() {
var divname = $(this).attr("name");
alert(divname);
/* WORK FINE TIL HERE */
/* THIS IS THE REAL PROBLEM */
$(".item" + divname).show("slow").siblings().hide("slow");
/* ALERT IF YOU FIND THE DIV WITH THE ID, DOES NOT WORK */
if ($(".item" + divname)[0]) {
alert('tonton');
}
});
I'm using jQuery, basic HTML and CSS, and PHP is not allowed.

Your function that is supposed to give the div's their IDs is giving them a class. You should change it to something like this:
$("#capsule_player > div").each(function(i){
$(this).attr("id", 'item' + (i+1));
});
That should work, but the rest of the code could do with a tidyup as there a better/more semantic ways to do what you want to do (which I might do when I'm not busy).
EDIT:
Something like this would be better (based on Armatus' comment):
// give each div a data-index attribute
$("div.item").each(function(i){
$(this).attr("data-index", i);
});
// give each anchor a data-index attribute
$("#video_grid .grid_item a").each(function(i) {
$(this).attr("data-index", i);
});
$(".grid_item a").live("click",function () {
var index = $(this).attr("data-index");
$('div.item[data-index="' + index + '"]').show();
});
.live() is deprecated, but I'll leave it because I don't know which version of jQuery you're using.

Although the route that Christian shows you is probably in the long run better and surely more learningful, your original problem can easily be solved by changing two lines:
$(this).attr('name', '#' + (i + 1));
[...]
$(this).addClass('item#' + (i + 1));
into
$(this).attr('name', 'Q' + (i + 1));
[...]
$(this).addClass('itemQ' + (i + 1));
The immediate problem is that you are giving your div a classname which includes a '#' sign. This will literally become part of your class name. However, during selection, this '#' sign will be interpreted as a 'ID' selector. So that doesn't work.

Related

JS/JQUERY How to give priority to a button click in the same DIV

My whole div is clickable and will change the page. However, inside my div, I have an element that is also clickable, but it should be prioritized sincee it stays on the page.
Basicly, i'm working on a webshop. clicking on a div will go to a new page with the requested data. However, the div includes a clickable image that adds the item to the wishlist.
In the code below, child refers to my whole clickable div, whereas my wishElement is the clickable image to refer to my wishlist.
$('#' + wishElement).click(function() {
window.location.href = "http://website.com/index.php?wish=" + child;
});
$('#' + child).click(function(){
window.location = "http://website.com/item.php?item=" + child + '&name=' + itemname + '&link=' + link;
});
Use event.stopPropagation(); to stop your child event from bubbling up:
$('#' + child).click(function(ev){
ev.stopPropagation();
window.location = "http://website.com/item.php?item=" + child + '&name=' + itemname + '&link=' + link;
});
My problem has been solved by the post coded above, however, the
ev.stopPropagation();
has to be inside my wishElement in order to work.
So thanks for the help!

How to change Jquery selector based on an param passed through a function

I have a function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index).attr('style', 'color: red');
console.log('index: ' + index);
console.log($("#" + index).text());
}
}
So my question is. The text color of the element changes color when I use $('#20') but when I use, $('#' + index) it doesn't work.
Funny thing is, I with console.log.. it logs the text of the element but I can't effect the css of it.
Why is this happening?
// after a three hour meeting.. I came back with some really great answers!! Thank you!!
edit:
the code below shows how I'm snagging all the links on the page and add the id equal to the index of that item. So that's why I'm trying to grab that link, and effect it in some way. I appreciate all you guys.. I think I'm going to take the string and add a letter to it as they come in through the function and then manipulate the anchor from that point. I just wonder if there's a more efficient way of doing this.
$(".lpage a").each(function (index) {
// console.log(index + ": " + $(this).text());
str = $(this).attr('href');
arrayOfSites.push(str);
str = arrayOfSites[index];
title = $(this).attr('title');
parseURL(str);
$('.colContent2').append(cellOpen + '<a onclick="whichFunction(' + index + ');" id= "' + index + '"style="cursor:pointer;" class="injectedLinkCol2" >' + str + '</a>' + cellClose).prop("id", index);
});
Maybe it has something to do with the name of your id attribute. Take a look at this answer.
Try to use the toString() function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index.toString()).attr('style', 'color: red');
console.log('index: ' + index);
console.log($( "#" + index.toString() ).text());
}
}
An id name or class name must begin with a name must begin with an underscore (_), a hyphen (-), or a letter(a–z).
So something like
'#d20'
would work.
See this: Valid CSS Selectors.
I couldn't reproduce the exact problem. I made a pen (link) and tried what you asked but it works well. So it must be some error in the remaining code.
on a related note
In CSS id's are not allowed to start with a number(classes are allowed). So writing something like
#20{
color: red;
}
won't work, but the rule only applies to css. JQuery will still work, which means your only option's are to write inline styles or use JQuery's .attr or .css, but jQuery.attr() will reset all your inline styles. you are left with using .css(). So, it's better to not start your id's with numbers.
try using .css instead of .attr and see if it works.
$('.exampleClass:eq(' + index + ')').css("color", "yellow");
for some reason works
$('.exampleClas').eq(index).css("color", "yellow");
does not work.

Jquery mouse over adding css

I have a p tag inside an anchor, there many be a variable number of instances of this during the loop. My goal is to on hover make the p tag expand and show more information. I have this so far in terms of mouseover.
however this is not working for me. does anyone have any ideas how to achieve this? someonehow i need to use the passed parameter 'e' to change the height
boxOPToneplustwo : this is an a tag as well.
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(e.target).next('p').addClass("popupHighlight");
});
element creation:
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPToneplustwo\" alt=\'"+ image_website +"' style=\"cursor:pointer;width:"+ itemWidth + "px"+";height:"+anchorHeight+";position:absolute;left:"+ locationLeft + "px"+";top:0.3%;\" ><p id=\"test\" class=\"popupDynamic\"> " + popupImageTitles[i] + "</p>";
anchorElement += '</a>';
with jQuery you can use this to refer to the handled element.
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(this).next('p').addClass("popupHighlight");
});
http://api.jquery.com/mouseover/
Console play
e.g: trying putting the following code in the console (F12) and see what it does to SO :P
$("p, span").mouseover(function(){ $(this).css("display", "none"); } );

Adding CR or LF in HTML attribute

To explain this shortly, I have an mouseenter Jquery event firing up an AJAX call. And a Jquery UI tooltip.
$(function()
{
$(document).tooltip({track:true});
$('#NewUser').mouseenter(function(){AJAXValidation("NewUser")});
});
Here is the call:
function AJAXValidation(section)
{
var request = $.ajax(
{
url: "ProcessJRT.php",
type: "POST",
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
data:
{
validate:section
}
});
request.done(
function(message)
{
var div = document.createElement('div');
$(div).html(message);
$(div).children().each
(
function(i)
{
var title = '';
if($('#' + $(this).attr('id')).attr('title') != null)
{
title = $('#' + $(this).id).attr('title');
}
title += $(this).html() + '\r\n';
$('#' + $(this).id).attr('title', title);
}
);
});
}
What it does now is it take the <div>s from message and it place them in a parent <div>. (In my code the div already exist, I changed that part so the question would stay as short as possible).
I then take the text from those <div> and I want to place them in the corresponding <input/> title attribute.
Everything work just perfect here exepte this stupid little thing:
I am unable to add a LN or a CR in the title so all the texts from the divs would be on separate line...
I have tried adding a </br> inside the attribute like this:
function(i)
{
var title = '';
if($('#' + $(this).id).attr('title') != null)
{
title = $('#' + $(this).attr('id')).attr('title');
}
title += $(this).html() + '</br>';//<---See I added a BR here
$('#' + $(this).id).attr('title', title);
}
But it display the </br> as normal text. I than tried String.fromCharCode(13) but did'nt work, I tried jus '\n' or '\r\n' and still does work.
Can someone point out were I am derping on this one??
Thanks!
EDIT:
Changed the $('#' + $(this).attr('id')) to $('#' + $(this).id).
You can't format the title attribute in that way, it doesn't work, and will be different across different browsers.
Try the jquery plugin qTip to achieve what you want. (looks good too!)
http://craigsworks.com/projects/qtip/
Alternatively, you can cheat by using etc, to push the text to the next line. but this is flaky at best.
Here is how I resolve my problem with the idea that #crush gave me:
First:
I removed the tooltip initialization from the function that fire the event :
$(function()
{
$('#NewUser').mouseenter(function(){AJAXValidation("NewUser")});
});
Next:
I changed the "done" function so I would initialise a new tooltip each time with html content (FYI JQuery tooltip can format HTML)
Here what it look like now:
function(message)
{
var div = document.createElement('div');
$(div).html(message);
var title = '';
$(div).children().each
(
function(i)
{
if($('#' + $(this).id).attr('title') != null)
{
title = $('#' + $(this).id).attr('title');
}
title += $(this).html() + '</br>';
$(document).tooltip({content:title, items:('#' + $(this).id)});
}
);
}

collapse field in Html

How to make fields in Html which may collapse if checkbox is chosen.
I am programming in Django.
regards,
Gintare
Touche Spacedman...
I'd recommend jquery as well ( http://jquery.com/ ) as it's very easy to use.
Here's some code whipped up in a heartbeat.
$("#my_checkbox").change( function() {
if ($(this).is(':checked')) {
$("#my_html").hide(); // hide element with id="my_html"
} else {
$("#my_html").show(); // show...
}
});
You need a javascript library, such as jQuery - then its easy to assign animation actions to events. Read the jQuery docs to learn, or cut and paste the solution that someone else will doubtless put here shortly...
Note this isn't a Django-specific problem, its javascript and html.
The jQuery code below uses an image of a '+' and then a header. e.g. + Top Ten
I used it to create an accordion.
$(document).ready(function () {
$("div#hideable div").hide();
// add css to show +/- symbols and labels - no point showing them if they don't work!
$("div#hideable h3 a img").css("display", "inline");
$("div#hideable label").css("display", "inline");
$("div#hideable h3 a").toggle(function () {
$($(this).attr("href")).show();
imgName = $(this).find('img').attr("src").split("-", 1); //grab the image name so that we get the right one
$(this).find('img').attr("src", imgName + "-minus.gif"); //change img, alt and label to match action
$(this).find('img').attr("alt", "-");
var sectionId = $(this).attr("href").substring($(this).attr("href").length - 1);
if (sectionId == 0) {
sectionId = 10;
}
labelName = "#lblSection" + sectionId;
$(labelName).text("click '-' to collapse");
}, function () {
$($(this).attr("href")).hide();
$(this).find('img').attr("src", imgName + "-plus.gif");
$(this).find('img').attr("alt", "+");
var sectionId = $(this).attr("href").substring($(this).attr("href").length - 1);
if (sectionId == 0) {
sectionId = 10;
}
labelName = "#lblSection" + sectionId;
$(labelName).text("click '+' to expand");
});
});

Categories

Resources