I need some help with JQuery.
In my site I have a button that repeats in a layout. I decided to differentiate them by adding a class to each of them with a number with this code below which works very well.
jQuery(document).ready(function() {
// each button in the Machine loop get a unique CLASS
jQuery(".rv_button").each(function(i) {
jQuery(this).addClass("item" + (i + 1));
var its = ("item" + (i + 1));
console.log("." + its);
});
});
This button will be used to make appear or disappear a section that I also decided to differentiate them by adding a class to each of them with a number with this code below which works very well.
jQuery(".reveal").each(function(f) {
// each section in the Machine loop get a unique CLASS
jQuery(this).addClass("rive" + (f + 1));
var id = ("rive" + (f + 1)); // each section in the Machine loop get a unique CLASS
console.log("." + id);
});
I would like to create a code which has the function of when I click on item1 -> rive1 appears and disappears etc ...
here is my test code which does not work because I do not know how to include the variable included previously.
var id;
var its;
jQuery(document).ready(function() {
// The section is HIDE with the new class
jQuery("." + id).hide();
// The click function on the new button class
jQuery("." + its).click(function(e) {
// when i click on the new class button, the section appaear or desapear.
e.preventDefault();
jQuery("." + id).slideToggle();
jQuery("." + its).toggleClass('opened closed');
});
});
Any idea on how to passing the Variable into the last function ?
thanks all !
This the entire code :
jQuery(document).ready(function() {
// each button in the Machine loop get a unique CLASS
jQuery(".rv_button").each(function(i) {
jQuery(this).addClass("item" + (i + 1));
var its = ("item" + (i + 1));
console.log("." + its);
});
jQuery(".reveal").each(function(f) {
// each section in the Machine loop get a unique CLASS
jQuery(this).addClass("rive" + (f + 1));
var id = ("rive" + (f + 1)); // each section in the Machine loop get a unique CLASS
console.log("." + id);
});
var id;
var its;
jQuery(document).ready(function() {
// The section is HIDE with the new class
jQuery("." + id).hide();
// The click function on the new button class
jQuery("." + its).click(function(e) {
// when i click on the new class button, the section appaear or desapear.
e.preventDefault();
jQuery("." + id).slideToggle();
jQuery("." + its).toggleClass('opened closed');
});
});
});
Related
I have a generator that generates random entries from people. My goal is to mouseover an entry and have that highlight all of the other entries from that user. Each entry gets assigned two classes, one which is the name of the user.
Here's the code I have below.
$(document).ready(function(){
var $body = $('div.center');
$body.html('<header><p id="headertext">Twittler</p></header>');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = "tweets"></div>');
$($tweet).addClass(tweet.user);
//I'm trying to have two classes here, and the ID. Probably don't need the ID.
$($tweet).attr("id",tweet.user);
$tweet.text('#' + tweet.user + ': ' + tweet.message + Date().toString("hh:mm tt"));
$tweet.appendTo($body);
index -= 1;
}
$("#tweetButton").click('click', function(){
index = 10;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = "tweets"></div>');
$($tweet).addClass(tweet.user);
//I'm trying to have two classes here, and the ID. Probably don't need the ID.
$($tweet).attr("id",tweet.user);
$tweet.text('#' + tweet.user + ': ' + tweet.message + Date().toString("hh:mm tt"));
$tweet.appendTo($body);
index -= 1;
}
$('.tweets').on('mouseover',function(){
var idget = $(this).attr('class');
$('div.center').find(idget).css('background-color','pink');
});
});
}); //Ends Script area
The tweets on mouseover entry at the bottom is my attempt at doing this, but when I mouseover an entry nothing happens. I'd definitely appreciate your help on what I'm missing here to make this happen.
so if I'm reading your code right (the onmouseover bit).. you grab the value of the class attribute and place it in the idget variable. In this case that value will be "tweets". Next you request all "tweets" (as a selector) that are children of any div element with a center css class attribute, and set its background color.
If all that is correct, "tweets" is not a valid selector, unless you have markup that looks like: <tweets></tweets>. I believe you want:
$('div.center').find('.' + idget).css('background-color','pink');
I don't know your html page but my best guest is this:
first of all you can't use id for tweet.user because there can't be more than one element with same id so I suggest this code for #tweetButton:
$("#tweetButton").click('click', function(){
index = 10;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = "tweets"></div>');
//$($tweet).addClass(tweet.user);
//I'm trying to have two classes here, and the ID. Probably don't need the ID.
$($tweet).attr("userid",tweet.user);
$tweet.text('#' + tweet.user + ': ' + tweet.message + Date().toString("hh:mm tt"));
$tweet.appendTo($body);
index -= 1;
}
for mouseover you should do this :
$('div.center').on('mouseover','.tweets',function(){
var idget = $(this).attr('userid');
$('div.center').find('[userid="'+idget+'"]').css('background-color','pink');
});
I'm trying to make a simple plugin that collects the # of Facebook likes and tweets for a given URL (and let users tweet or like a given link). There is a total share count that expands to include LIs for likes and shares upon hover. Currently, on mouseover or select of the like/share LIs, the HTML of the Twitter/Facebook is replaced with a link and text with a subtle CTA. This link is supposed to open a new window with a share dialog for the given social site. However, this link doesn't seem to work at all.
HTML
<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div id="social">
<ul>
<li class="share">
<p>shares<p>
</li>
<li class="twitter"><p>tweets</p></li>
<li class="facebook"><p>likes</p></li>
</ul>
</div>
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/app.js"></scrpt>-->
</body>
</html>
jQuery
var fbCount,twCount,totalCount,
urlDebug = 'http://www.google.com',
urlCurrent = window.location.href,
twitterCountUrl = 'http://urls.api.twitter.com/1/urls/count.json?url=' + urlDebug + '&callback=?',
facebookCountUrl = 'https://graph.facebook.com/fql?q=SELECT%20share_count,%20like_count,%20comment_count,%20total_count,commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27' + urlDebug + '%27',
fbShareUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlDebug + "&t=" + document.title + 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600',
twShareUrl = "https://twitter.com/intent/tweet?text=" + document.title + "url=" + urlDebug;
$('.sharelink').on('click', function() {
window.open( $(this).attr('href') );
return false;
});
function getnumString(num) {
var numString;
if (num < 1000) {
numString = num;
} else if (num < 10000) {
// removed my rube goldberg contraption and lifted
// CMS version of this segment
numString = num.charAt(0) + ',' + num.substring(1);
} else if (num < 1000000) {
numString = (Math.round((num / 1000) * 10) / 10) + "k"
} else {
numString = (Math.round((num / 1000000) * 10) / 10) + "M"
}
return numString.toString();
}
$.when(
$.getJSON(twitterCountUrl, function twitterCount(data) {
twCount = data.count;
$('.twitter').append('<p class="num">' + getnumString(twCount) + '</p>');
}),
$.getJSON(facebookCountUrl,
function facebookCount(data) {
fbCount = data.data[0].like_count;
$('.facebook').append('<p class="num">' + getnumString(fbCount) + '</p>');
})).done(function(response) {
totalCount = fbCount + twCount;
$('.share').append('<p class="num">' + getnumString(totalCount) + '</p>');
});
$('#social ul').on('mouseover touchstart focusin', function() {
$('.facebook, .twitter').slideDown("slow");
}).on('mouseleave touchend focusout', function() {
$('.facebook, .twitter').hide();
});
$('#social .twitter').on('mouseenter focusin', function() {
$(this).html('TWEET<br>LINK');
$(this).children('a').addClass('sharelink');
}).on('mouseleave focusout', function() {
$(this).children('a').removeClass('sharelink');
$(this).html('<p> tweets</p>').append('<p class="num">' + getnumString(twCount) + '</p>');
});
$('#social .facebook').on('mouseenter focusin', function() {
$(this).html('SHARE<BR>ON FB');
$(this).children('a').addClass('sharelink');
}).on('mouseleave focusout', function() {
$(this).children('a').removeClass('sharelink');
$(this).html('<p>likes</p>').append('<p class="num">' + getnumString(fbCount) + '</p>');
});
When you add dynamic elements to DOM jQuery actually never cached that. You need to use delegated events so that when you add dynamic elements they are in scope and jQuery is listening
Case 1 (direct):
$("div#social .twitter").on("mouseenter focusin", function() {...});
== Hey! I want every span.twitter inside div#social to listen up: when you get mouseenter on, do X.
Case 2 (delegated):
$("div#social").on("mouseenter focusin", "span.twitter", function() {...});
== Hey, div#target! When any of your child elements which are "span.twitter" get mouseentered, do X with them.
Summary
In case 1, each of those spans has been individually given instructions. If new spans get created, they won't have heard the instruction and won't respond to clicks. Each span is directly responsible for its own events.
In case 2, only the container has been given the instruction; it is responsible for noticing clicks on behalf of its child elements. The work of catching events has been delegated.
I'm looking to cycle through the dom and add an ID attribute to an existing table element. Can't quite seem to get it working. Basicaly the code looks for a table that has a specific class, then adds an ID. More things will happen depending on the tables class but for the moment I'm stuck on adding the ID. Any help would be greatly appreciated.
$(document).ready(function () {
var chartTypeArray = [];
var i = 0;
// cycle tables add id and store class
$('table').each(function (i) {
if ($(this).hasClass('bar')) {
chartTypeArray.push('bar');
$(this).attr('ID', 'tableToChart' + i);
} //end bar
else if ($(this).hasClass('line')) {
chartTypeArray.push('line');
$(this).attr('ID', 'tableToChart' + i);
} //end line
else if ($(this).hasClass('area')) {
chartTypeArray.push('area');
$(this).attr('ID', 'tableToChart' + i);
} //end area
else if ($(this).hasClass('pie')) {
chartTypeArray.push('pie');
$(this).attr('ID', 'tableToChart' + i);
} //end pie
i++;
console.log('Table ' + i + ' is a ' + $(this).attr('class') + ' chart');
}); //end function
}); //end of document ready
try with lower case
$(this).attr('id', 'tableToChart' + i);
also you don't have to do
var i = 0; //outside the each loop
// and you don't need
i++; // inside the each loop
I've created a JSfiddle here:
basically I have a form that will allow users to input additional sections... but when I have added more than 2 units and then proceed to click on the 'plus' (+) icon I get more than 1 element created in that section... its probably something elementary, but any info will help.
Move your Click functions out of the click function
//add unit input box and increment click counter by one.
addUnit.click(function () {
unitCounter += 1;
unitElementCount = jQuery(".unit-element").length;
if (unitCounter <= 4) {
error.hide();
container.append('<table id="unit-' + unitCounter + '-div" class="create-course-table-element unit-element"><tr><td><label class="unit-label">Unit ' + unitCounter + '</label></td><td><input class="create-course-input-element unit-input" id="unit-id-' + unitCounter + '" name="unit-' + unitCounter + '" /><div id="delete-unit-' + unitCounter + '" class="ui-icon ui-icon-circle-close del-unit" title="Delete unit"></div></td></tr><tr><td align="center">Sections</td><td><div id="add-section-icon-' + unitCounter + '" class="ui-icon ui-icon-plus add-section-icon"></div></td></tr></table><div id="section-id-' + unitCounter + '-div" class="this-section"></div>');
} else if (unitElementCount == 4) {
unitCounter = 5;
error.html("");
error.fadeIn(1500);
error.append("<p class='error-message'>Note: You are only able to add 4 units to a given course. Each unit allows you to add 10 separate sections of content; therefore you may add a total of 40 different sections to a given course. If the material requires more units, you should consider dividing the course into 2 parts.</p>");
}
});
//This part has been slightly modified and moved out of the addUnit.click() function
var counterSecTwo = 0;
var counterSecThree = 0;
var counterSecFour = 0;
jQuery(document).on("click", "#add-section-icon-2",function () {
counterSecTwo += 1;
var container = jQuery("#section-id-2-div");
container.append("<p>test "+counterSecTwo+"</p>");
});
jQuery(document).on("click", "#add-section-icon-3",function () {
counterSecThree += 1;
var container = jQuery("#section-id-3-div");
container.append("<p>test "+counterSecThree+"</p>");
});
jQuery(document).on("click", "#add-section-icon-4",function () {
counterSecFour += 1;
var container = jQuery("#section-id-4-div");
container.append("<p>test "+counterSecFour+"</p>");
});
});
Here I am binding the click handlers to Document as the elements do not exist yet: you could also add the event listener when you create the actual element.
Modified fiddle: http://jsfiddle.net/vewP7/
Ok, below is my code:
for (var mycounter = currentcanvas.getObjects().length; mycounter > 0; mycounter--) {
var id = currentcanvas.getObjects().length - mycounter;
alert(id);
$("#frontlayers").prepend('<li id="' + id + '" class="layers"></span> Layer ' + (id + 1) + ': ' + " " + ' </li>');
$("#" + id).click(function(e) {
alert(id);
});
}
This correctly adds the li with the text "Layer 1" and "Layer 2", but when I click on them the alert is always 2 instead of 0 and 1 accordingly.
does anyone know why this is happening? sorry I'm relatively new to jQuery.
This is a good use for $.each because using a handler function avoids the scope issue you have with the closure on the variable i:
$.each(currentcanvas.getObjects(), function(i, v) {
var id = i; // nb: numeric ID fields only allowed in HTML5
$('<li>', {
id: id,
'class': 'layers',
text: 'Layer ' + (id + 1) + ': '
}).appendTo('#frontlayers').on('click', function(e) {
alert(id);
});
});
That said, since your ID is stored on the clicked element anyway, you could have just used that directly - this.id