In my program I have a class called "right-answer that I want in the td class but I am having real trouble with it.
This is where I add the "right word" class to "spellWord". But how to I add it to the "td" class instead.
var spellWord = $('.highlight-problem .drop-box');
if (!spellWord.filter(':not(.occupied)').length) {
var wordIsCorrect = 0;
spellWord.each(function () {
if ($(this).parents('td').data("letter") == $(this).find("div").data("letter")) {
console.log('letter is: ' + $(this).find("div").data("letter"))
wordIsCorrect++;
}
});
console.log(spellWord.length + ' , ' + wordIsCorrect);
if (spellWord.length == wordIsCorrect) {
spellWord.addClass('right-word');
$(right).css('visibility', 'visible');
$(wrong).css('visibility', 'hidden');
score.right++;
$('.score').html(score.right + "/2").show();
setTimeout(function() {
successSound.play();
}, 200);
I have tried things like.
spellWord.addClass('td').addClass('right-word');
and
$('.td').addClass('right-word');
But cannot seem to get it working. Fiddle: http://jsfiddle.net/smilburn/Dxxmh/93/
If the spellWord element is inside the td, use parent():
spellWord.parent().addClass('right-word');
Note that parent() will only give you the direct ancestor, use parents() instead if you nede to go higher.
closest(), siblings(), or find() may also be helpful, depending on where the td is in relation to the spellWord element.
Try .closest()
spellWord.closest('td').addClass('right-word');
td is the parent of the spellWord.. So you need to go to its td ancestor and then add the class
Related
I have a javascript method that has 2 parameters, the first is the ID of a tr element, the other is an actual div. My add/remove class jQuery method works fine for the first item (which I get with a jQuery selector). However it throws a javascript error when I use it on the passed in Div.
onclick="ToggleTicketDetails('ticketDetails_#(ticket.TicketID)', this);"
I can obviously use a jQuery selector on the div to fix this, however I would like to know why it behaves this way.
function ToggleTicketDetails(detailsId, divSender) {
//alert(divSender);
var element = $('#' + detailsId);
//alert(element);
if (element.hasClass("TicketDetailsOff")) {
element.removeClass("TicketDetailsOff").addClass("TicketDetailsOn");
divSender.removeClass("DivAsExpand").addClass("DivAsCollapse");
}
else {
element.removeClass("TicketDetailsOn").addClass("TicketDetailsOff");
divSender.removeClass("DivAsCollapse").addClass("DivAsExpand");
}
}
divSender is DOM element. Use jquery object $(divSender) to apply removeClass and addClass on this like below.
function ToggleTicketDetails(detailsId, divSender) {
var element = $('#' + detailsId);
if (element.hasClass("TicketDetailsOff")) {
element.removeClass("TicketDetailsOff").addClass("TicketDetailsOn");
$(divSender).removeClass("DivAsExpand").addClass("DivAsCollapse");
}
else {
element.removeClass("TicketDetailsOn").addClass("TicketDetailsOff");
$(divSender).removeClass("DivAsCollapse").addClass("DivAsExpand");
}
}
Since I want to use classes instead of id's in these functions(I have three of the same function with different things I want to .append) I am sure I need to put $(this) in those functions somewhere to only trigger only ONE function on button click and not all three of them. but I am not sure because I am a total beginner in jquery/js, so I would appreciate some help.
$(document).ready(function () {
$(".onclick").click(function () {
$('#favorites').append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
http://codepen.io/anon/pen/JYxqEw - HTML And the Jquery Code
$('.onclick') selects all the elements with a class of onclick. That means that, whenever something with class="onclick" is clicked, that function will fire.
If you want all of those elements to append that exact HTML to the #favorites element, then you can leave your code as-is.
However, if what you're trying to do is append that html to the clicked element, that is when you'd use $(this) -- that selects the element you clicked with jQuery, then you can append directly to that element ie:
$(document).ready(function () {
$(".onclick").click(function () {
// this will append the HTML to the element that triggered the click event.
$(this).append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
EDIT
so to insert the contents of each .onclick into #favorites, you'll need to use the innerHTML value of the DOM node. example fiddle:
http://jsbin.com/qazepubuzu/edit?html,js,output
When you select something with jQuery, you're actually getting back not just the DOM node, but a jQuery object -- this object contains both a reference to the actual DOM node ([0]), as well as a jquery object ([1]).
So to select the DOM node with $(this), you target the node: $(this)[0]. Then you can use .innerHTML() to grab the HTML contents of the node and do as you like.
Final result:
$(function () {
$('.onclick').click(function () {
$('#favorites').append( $(this)[0].innerHTML );
});
});
So the building blocks are not that complex, but I think you're a novice jQuery developer and so you may not be clear on the difference between jQuery and JS yet.
$(selector, context) allows us to create a jQuery collection for a CSS selector which is the child of a current context DOM node, though if you do not specify one there is an automatic one (which is document.body, I think). Various functions iterating over jQuery collections make the particular element available as this within the JavaScript. To get to the strong element from the .onclick element in the HTML fragment you need to travel up in the hierarchy, then to the appropriate element. Then, we can collect the text from the element. We can do this in either JS or jQuery.
To do this with simply jQuery:
// AP style title case, because Chicago is too crazy.
var to_title_case = (function () { // variable scope bracket
var lower_case = /\b(?:a|an|the|and|for|in|so|nor|to|at|of|up|but|on|yet|by|or)\b/i,
first_word = /^(\W*)(\w*)/,
last_word = /(\w*)(\W*)$/;
function capitalize(word) {
return word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
}
function capitalize_mid(word) {
return lower_case.exec(word) ? word.toLowerCase() : capitalize(word);
}
return function to_title_case(str) {
var prefix = first_word.exec(str),
str_minus_prefix = str.slice(prefix[0].length),
suffix = last_word.exec(str_minus_prefix),
center = str_minus_prefix.slice(0, -suffix[0].length);
return prefix[1] + capitalize(prefix[2]) + center.replace(/\w+/g, capitalize_mid)
+ capitalize(suffix[1]) + suffix[2];
};
})();
$(document).ready(function() {
$(".onclick").click(function () {
var text = $(this).parents('.ui-grid-a').find('.ui-block-a').text();
var html = '<div data-role="main"class="ui-content">'
+ '<div class="ui-grid-b"><div class="ui-block-a">'
+ to_title_case(text) + '</div><div class="ui-block-b">More Info</div>'
+ '<div class="ui-block-c">Unfavorite</div></div></div>';
$("#favorites").append(html);
});
});
My goal is on hover a p element contained inside an a tag gets bigger on hover. I have achieved this via css3 transitions, however this is not the issue.
A loop creates a variable amount of elements in the form below on each iteration.
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPT oneplustwo\" 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>';
I would love to be able to add a mouse in/out effect whenever the user scrolls on the relevant anchor. each p tag contains unique information that needs to be conveyed and on hover only the relevant one should react.
I dont want to it it the below way, making two each of the methods every time a new element is created above. is there a way to have the following below which will work for a dynamic amount of elements?
$("#anchor" + etc).mouseover(function() {
document.getElementById("test").style.height="1.1em";
});
$("#anchor" + etc).mouseout(function() {
document.getElementById("test").style.height="1.1em";
});
My version of suggestions. the console logs works.
.popupHighlight {
color: red;
}
..
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(e.target).next('p').addClass("popupHighlight");
});
$('.boxOPToneplustwo').mouseout(function (e) {
$(e.target).next('p').removeClass("popupHighlight");
});
What about selecting all a elements?
$('a').mouseout(function() {
//do stuff in here
});
or better yet, have a class selector:
$('.mySpecialRolloverClass').mouseover(function (e) {
$(e.target).next('p').addClass("highlight");
});
$('.mySpecialRolloverClass').mouseout(function (e) {
$(e.target).next('p').removeClass("highlight");
});
which would go hand in hand with
An anchor
and
.highlight {
color:red;
}
Here's a jsfiddle demo:
http://jsfiddle.net/8J6kM/
The #yochannah answer is correct, however if you want to add more links dynamically, you then need to use on method instead of mouseover and mouseout, otherwise it won't work. See the demo and jQuery documentation for further details.
// I assumed that links are placed inside of a container element: #links
$('#links').on('mouseover', '.mySpecialRolloverClass', function (e) {
$(e.target).next('p').addClass("highlight");
});
I am using this to point a seperate td's in a table. And the id(dynid) are created dynamically so i need to change the position to absolute when user hover on a td. And i tries the below one but its not wroks
$('#selectTable tr td #td'+dynid).hover(
function () {
$(this).css("position","absolute");
}
);
Thanks in advance
You are looking for an element within the td element, but you want the td element with a certain id. There is whitespace. You need td#id instead of td #id.
dynid = 2; // Test
$('#selectTable tr td#td' + dynid).hover(
function () {
$(this).css("position","absolute");
}
);
A sample with background-color
http://jsfiddle.net/FKhbd/
You may want to define a second handler, if the hover ends. Something like this:
$('#selectTable tr td#td' + dynid).hover(
function () {
$(this).css("position","absolute");
},
function () {
$(this).css("position","relative");
}
);
Probably your selector is wrong: '#selectTable tr td #td'+dynid should become '#selectTable tr td#td'+dynid. You'd also be wise to toggle on and off a css class that sets position: absolute like so:
$("#selectTable td").hover(function () {
$(this).addClass("pos-abs"); // focus
}, function () {
$(this).removeClass("pos-abs"); // blur
});
See http://api.jquery.com/hover/
I'm currently using this to get the class for a specific bit of HTML on the page:
$(this).parent("div").attr('class')
But that div has multiple classes: current_status status_billed
My end goal here is to grab the class that starts with status_ and replace it with a different class name.
So using my .parent() function above, I'm able to select the div I need, but I then need to remove the status_billed class and replace it with, for example, status_completed (or a number of other class names).
Select divs that have the status_billed class:
$(this).parent('div.status_billed')
Select divs whose class attribute contains status_:
$(this).parent('div[class*=status_]')
That's about the best you'll get with jQuery selectors. You can do better using .filter():
$(this).parent('div').filter(function ()
{
var classes = $(this).attr('class').split(' ');
for (var i=0; i<classes.length; i++)
{
if (classes[i].slice(0,7) === 'status_')
{
return true;
}
}
return false;
});
...but I'm not sure why you're doing all this - .parent() returns at most 1 element. Did you mean .closest() or .parents()?