Where do I put $(this) in the function? - javascript

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);
});
});

Related

2nd function in toggle function not working

I want to toggle the width of an element on click of another.
I've used the script someone has made here: http://jsbin.com/ohOZEYI/1/edit?html,css,js,output
and just replaced it with my own elements:
function a(el){
$(el).animate({width: "10%"}, 1500);
}
function b(el){
$(el).animate({width: "100%"}, 1500);
}
$("#mybtn").click(function() {
var el = $('#container');
return (el.t = !el.t) ? a(el) : b(el);
});
The first function (a) works fine and shrinks the element to 10% width. But the 2nd function doesnt work.
Would anyone know why?
The jQuery function doesn't return DOM nodes. It returns an object that contains a collection of DOM nodes.
var el = $('#container');
creates a new instance of an object which happens to contain a reference to the DOM node with an ID of container. Every time the function gets called, you get a brand new instance of el, which means your toggle can never toggle.
To fix this, you're going to want to store the toggle data on the DOM node.
Use the .data() method:
var t = el.data('toggle');
if (t) {
a(el);
} else {
b(el);
}
el.data('toggle', !t);

jQuery slideDown not working on element with dynamically assigned id

EDIT: I cleaned up the code a bit and narrowed down the problem.
So I'm working on a Wordpress site, and I'm trying to incorporate drop-downs into my menu on mobile, which means I have to use jQuery to assign classes and id's to my already existing elements. I have this code that already works on premade HTML, but fails on dynamically created id's.
Here is the code:
...
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
$(document).on('click', '.dropdown-title', function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
//THIS LINE FAILS
$(currentAttrValue).slideDown(300).addClass('d-open');
}
e.preventDefault();
});
I've registered the elements with the class dropdown-title using $(document).on(...) but I can't figure out what I need to do to register the elements with the custom ID's. I've tried putting the event callback inside the .each functions, I've tried making custom events to trigger, but none of them will get the 2nd to last line of code to trigger. There's no errors in the console, and when I console log the selector I get this:
[ul#m0.sub-menu.dropdown-content, context: document, selector: "#m0"]
0
:
ul#m0.sub-menu.dropdown-content
context
:
document
length
:
1
selector
:
"#m0"
proto
:
Object[0]
So jQuery knows the element is there, I just can't figure out how to register it...or maybe it's something I'm not thinking of, I don't know.
If you are creating your elements dynamically, you should be assigning the .on 'click' after creating those elements. Just declare the 'on click' callback code you posted after adding the ids and classes instead of when the page loads, so it gets attached to the elements with .dropdown-title class.
Check this jsFiddle: https://jsfiddle.net/6zayouxc/
EDIT: Your edited JS code works... There also might be some problem with your HTML or CSS, are you hiding your submenus? Make sure you are not making them transparent.
You're trying to call a function for a attribute, instead of the element. You probably want $(this).slideDown(300).addClass('d-active'); (also then you don't need $(this).addClass('d-active'); before)
Inside submenus.each loop add your callback listener.
As you are adding the class dropdown-title dynamically, it was not available at dom loading time, that is why event listener was not attached with those elemnts.
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
// add callback here
$(this).click( function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
$(currentAttrValue).slideDown(300).addClass('d-active');
}
e.preventDefault();
});
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
Turns out my problem is that jQuery is adding to both the mobile menu and the desktop menu, where the desktop menu is being loaded first when I search for that ID that's the one that jQuery finds. So it turns out I was completely wrong about my suspicions.

How to simplify code to add new elements to a page with jQuery?

I've written the following code to add a clickable "link button" to a section of my page.
var linkButtonHtml = "<a data-makeId='" + makeId + "' href='javascript:expandMake(" + makeId + "," + categoryId + ")'>+</a> " + makeName;
var divHtml = "<div style='display:none' class='models' data-makeId='" + makeId + "'></div>" + "<br/>";
html += linkButtonHtml + divHtml;
$('#linkDiv').html(html);
The code works fine, but it's ugly and difficult to read with all the string concatenation.
As you can see, I am building anchor elements and div elements with string concatenation. The target of my anchor element is a javascript function invocation with two arguments. Is there a good jQuery way to improve the readability of this code?
I'm not sure if this really improves readability is here is a 100% jQuery solutions:
$(html)
.append(
$('<a />')
.attr('data-makeId', makeId)
.attr('href', 'javascript:void(0);')
.click(function(event)
{
// Prevent clicking the link from leaving the page.
event.preventDefault();
expandMake(makeId, categoryId);
})
.text('+'))
.append(
document.createTextNode(makeName)
)
.append(
$('<div />')
.addClass('models')
.attr('data-makeId=', makeId)
.hide());
Where "html" in $(html) is the html variable you have in your sample.
jQuery offers an option for a second argument when creating elements.
var linkButton = $('<a>',{'data-makeId':makeId,
href:'#',
click:function(){expandMake( makeId, categoryId )},
text:'+'
});
var div = $('<div>',{ style:'display:none',
'class':'models',
'data-makeId': makeId
})
.after('<br>');
$('#linkDiv')
.empty()
.append(html)
.append(linkButton)
.append( makeName )
.append(div);
EDIT: Fixed an issue where makeName was not appended.
Only real way is either abstracting some of your tag generation or spread the script out a little to make it more readable : http://jsfiddle.net/3dYPX/1/
Your also using jQuery so you might want to consider changing the way you trigger the javascript. Try looking into the .live() event. (Ill just get an example up, not that its very important)
Using live event for unobtrusive javascript:
http://jsfiddle.net/3dYPX/2/
It is all being done inside of the onLoad event at the moment, just to use as an example.
Use a template library such as
jQuery Templates instead of inlining
HTML.
Instead of using "javascript:" URLs, attach event handlers to the generated DOM fragments.
Refrain from using inline styles.
Something like:
$('#linkDiv')
.empty()
.append($.tmpl(myTemplate, {
makeId: makeId,
makeName: makeName,
categoryId: categoryId
}))
.click(function () {
var makeId = $(this).attr("data-makeId");
if (makeId) {
expandMake(makeId, $(this).attr("data-categoryId"));
}
});
Where myTemplate has the content:
${makeName}
<div class="models" data-makeId="${makeId}"></div>
Instead of using an inline style to initially hide the models, hide them all with a general CSS rule, and then selectively show them with a class:
.models { display: none }
.models.shown { display: block }
Just add the "shown" class to show a certain block of models.
Here you go:
$('#linkDiv').empty().append([
$('+').data('makeId', makeId).click(function(e) {
e.preventDefault();
expandMake(makeId, categoryId);
})[0],
$('<span>').text(makeName)[0],
$('<div class="models">').data('makeId', makeId).hide()[0],
$('<br>')[0]
]);
Live demo: http://jsfiddle.net/cncbm/1/
Consider this:
$('#linkDiv').data({'makeId': makeId, 'categoryId': categoryId}).empty().append([
$('+').click(expandMake)[0],
$('<span>').text(makeName)[0],
$('<div class="models">').hide()[0]
]);
So, you define that data-stuff on the parent DIV (the common parent) and you re-factor the expandMake function so that it reads those data-values from the parent DIV instead of passing them as arguments.

how to get outerHTML with jquery in order to have it cross-browser

I found a response in a jquery forum and they made a function to do this but the result is not the same.
Here is an example that I created for an image button:
var buttonField = $('<input type="image" />');
buttonField.attr('id', 'butonFshi' + lastsel);
buttonField.val('Fshi');
buttonField.attr('src', 'images/square-icon.png');
if (disabled)
buttonField.attr("disabled", "disabled");
buttonField.val('Fshi');
if (onblur !== undefined)
buttonField.focusout(function () { onblur(); });
buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
buttonField.click(function () { fshiClicked(lastsel.toString()); });
And I have this situation:
buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>
The function is:
$.fn.outer = function(val){
if(val){
$(val).insertBefore(this);
$(this).remove();
}
else{ return $("<div>").append($(this).clone()).html(); }
}
so like this I loose the handlers that I inserted.
Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!
You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.
$('#old-button').after(buttonField).remove();`
after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.
Try this one:
var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);
:)
Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.
Consider the following HTML:
<span>My example</span>
Consider the following call:
var span = $("span").outerHTML();
The variable span is equal <span>My example</span>.
In the link above you can find more example in how to use .outerHTML() plug-in.
This should work fine:
var outer = buttonField.parent().html();

Can someone explain the following javascript code?

In addition to the explanation, what does the $ mean in javascript? Here is the code:
var ZebraTable = {
bgcolor: '',
classname: '',
stripe: function(el) {
if (!$(el)) return;
var rows = $(el).getElementsByTagName('tr');
for (var i=1,len=rows.length;i<len;i++) {
if (i % 2 == 0) rows[i].className = 'alt';
Event.add(rows[i],'mouseover',function() {
ZebraTable.mouseover(this); });
Event.add(rows[i],'mouseout',function() { ZebraTable.mouseout(this); });
}
},
mouseover: function(row) {
this.bgcolor = row.style.backgroundColor;
this.classname = row.className;
addClassName(row,'over');
},
mouseout: function(row) {
removeClassName(row,'over');
addClassName(row,this.classname);
row.style.backgroundColor = this.bgcolor;
}
}
window.onload = function() {
ZebraTable.stripe('mytable');
}
Here is a link to where I got the code and you can view a demo on the page. It does not appear to be using any framework. I was actually going through a JQuery tutorial that took this code and used JQuery on it to do the table striping. Here is the link:
http://v3.thewatchmakerproject.com/journal/309/stripe-your-tables-the-oo-way
Can someone explain the following
javascript code?
//Shorthand for document.getElementById
function $(id) {
return document.getElementById(id);
}
var ZebraTable = {
bgcolor: '',
classname: '',
stripe: function(el) {
//if the el cannot be found, return
if (!$(el)) return;
//get all the <tr> elements of the table
var rows = $(el).getElementsByTagName('tr');
//for each <tr> element
for (var i=1,len=rows.length;i<len;i++) {
//for every second row, set the className of the <tr> element to 'alt'
if (i % 2 == 0) rows[i].className = 'alt';
//add a mouseOver event to change the row className when rolling over the <tr> element
Event.add(rows[i],'mouseover',function() {
ZebraTable.mouseover(this);
});
//add a mouseOut event to revert the row className when rolling out of the <tr> element
Event.add(rows[i],'mouseout',function() {
ZebraTable.mouseout(this);
});
}
},
//the <tr> mouse over function
mouseover: function(row) {
//save the row's old background color in the ZebraTable.bgcolor variable
this.bgcolor = row.style.backgroundColor;
//save the row's className in the ZebraTable.classname variable
this.classname = row.className;
//add the 'over' class to the className property
//addClassName is some other function that handles this
addClassName(row,'over');
},
mouseout: function(row) {
//remove the 'over' class form the className of the row
removeClassName(row,'over');
//add the previous className that was stored in the ZebraTable.classname variable
addClassName(row,this.classname);
//set the background color back to the value that was stored in the ZebraTable.bgcolor variable
row.style.backgroundColor = this.bgcolor;
}
}
window.onload = function() {
//once the page is loaded, "stripe" the "mytable" element
ZebraTable.stripe('mytable');
}
The $ doesn't mean anything in Javascript, but it's a valid function name and several libraries use it as their all-encompassing function, for example Prototype and jQuery
From the example you linked to:
function $() {
var elements = new Array();
for (var i=0;i<arguments.length;i++) {
var element = arguments[i];
if (typeof element == 'string') element = document.getElementById(element);
if (arguments.length == 1) return element;
elements.push(element);
}
return elements;
}
The $ function is searching for elements by their id attribute.
This function loops through the rows in a table and does two things.
1) sets up alternating row style. if (i % 2 == 0) rows[i].className = 'alt' means every other row has its classname set to alt.
2) Attaches a mouseover and mouseout event to the row so the row changes background color when the user mouses over it.
the $ is a function set up by various javascript frameworks ( such as jquery) that simply calls document.getElementById
The code basically sets alternating table rows to have a different CSS class, and adds a mouseover and mouseout event change to a third css class, highlighting the row under the mouse.
I'm not sure if jQuery, prototype or maybe another third party JS library is referenced, but the dollar sign is used by jQuery as a selector. In this case, the user is testing to see if the object is null.
$ is the so-called "dollar function", used in a number of JavaScript frameworks to find an element and/or "wrap" it so that it can be used with framework functions and classes. I don't recognize the other functions used, so I can't tell you exactly which framework this is using, but my first guess would be Prototype or Dojo. (It certainly isn't jQuery.)
The code creates a ZebraTable "object" in Javascript, which stripes a table row by row in Javascript.
It has a couple of member functions of note:
stripe(el) - you pass in an element el, which is assumed to be a table. It gets all <tr> tags within the table (getElementsByTagName), then loops through them, assigning the class name "alt" to alternating rows. It also adds event handlers for mouse over and mouse out.
mouseover(row) - The "mouse over" event handler for a row, which stores the old class and background colour for the row, then assigns it the class name "over"
mouseout(row) - The reverse of mouseover, restores the old class name and background colour.
The $ is a function which returns an element given either the elements name or the element itself. It returns null if its parameters are invalid (non-existent element, for example)
I believe the framework being used is Prototype, so you can check out their docs for more info
Have a look at the bottom of the article that you have got the code from, you'll see that they say you'll also need prototype's $ function. From article
In your CSS you’ll need to specify a
default style for table rows, plus
tr.alt and tr.over classes. Here’s a
simple demo, which also includes the
other functions you’ll need (an Event
registration object and Prototype’s $
function).

Categories

Resources