How to push, pop, and wrap values in jQuery? - javascript

I've looked high and low and can't figure this one out!
On a page, I have links that have a certain class (plmore). On the same page, I have divs that have a certain class (fcontainer) among others. The number of links with the class plmore will always equal the number of div using the fcontainer class.
My question:
I need to wrap the divs that have fcontainer class with the links found using plmore.
PSEUDOCODE:
GET ARRAY OF HREFS
GET ARRAY OF DIV IDS
WRAP DIVS WITH HREFS
This is what I have so far:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
var hrefs = new Array();
$('a.plmore').each(function() {
hrefs.push($(this).find('a').attr('href'));
});
var features = new Array();
$('fcontainer').each(function() {
features.push($(this).find('div').attr('id'));
});
/* how does one pop from both arrays and wrap?? */
});
</script>

You mean like
jQuery(function ($) {
//find all the target anchor elements
var $as = $('a.plmore');
//find the div elements
$('.fcontainer').each(function (idx) {
//wrap the div at index idx using the href value of anchor element at index idx
$(this).wrap($('<a/>', {
href: $as.eq(idx).attr('href')
}))
});
});
Demo: Fiddle

Related

$(selector) equivalent in Ext 3

I have a menu component and I am trying to select the link selected by adding a class on click and removing the class from all menu items before adding it again to the newly clicked link.
So I simply find the parent component and query it to find all anchors. Then I try to chx the classes of all the anchors and remove the one/ones that are the "selected" class.
var anchors = component.el.query("a");
Ext.iterate(anchors, function(anchor, i){
anchor.removeClass('selected');
});
this.el.addClass('selected');
Does not work. Yet:
var anchors = component.el.query("a");
Ext.iterate(anchors, function(anchor, i){
$(anchor).removeClass('selected');
});
this.el.addClass('selected');
Does work.
What would be the Ext native equivalent to make this work?
With ExtJS 3 your anchors[index] will return the HTML for that specific node. To use addClass or removeClass you will need to use anchors.item(index);
Something like this would work:
Ext.onReady(function(){
var div = Ext.get('test'),
anchors = div.select("a"),
linkChangeClass = function (anchors, anchor) {
var index = anchors.indexOf(anchor);
anchors.removeClass('selected');
anchors.item(index).addClass('selected');
};
anchors.on('click', function() {
linkChangeClass(anchors, this);
});
});
Fiddle: http://jsfiddle.net/98c6a57e/

Get div id's of all divs with a specific class

I am trying to get div ids of all div elements having a specific CSS class.
I am able to get [object HTMLDivElement] by using getElementByClass but I haven't been able to get id from this object.
Basically, entirely I want to do is
get div ids of all div elements that have a specific CSS class,
get data-title of all div elements,
match data-title of these div elements with a string,
make display:none of all non-matching div elements.
Here is what I have tried:
function FilterFiles(filterItem) {
var elements = document.getElementsByClassName("listItem");
for (var i = 0; i < elements.length; i++) {
alert(elements[i].id);
// get div id of divs with data-title !=(not equal) filterItem
// make display:none of matching divs
}
}
Here is the Fiddle with actual HTML http://jsfiddle.net/6bo1rjrt/1/.
var temp = new Array();
var title = new Array();
function FilterFiles(filterItem) {
$('.listItem').each(function ()
{
temp.push($(this).attr("id")); //get id of each div to array
alert($(this).attr("id"));
title.push($(this).attr("data-title")); //get title of each div to array
if($(this).attr("data-title") != filterItem) //check non matching div
{
$(this).hide(); //hide div
}
});
}
first u loop throught all div with specific class with each, then check it's "data-title".
You can use attribute-not-equal-selector for that. also you need to give ids to div elements:
function FilterFiles(filterItem) {
var ids= $('.listItem[data-title!="'+filterItem+'"]').map(function(){
return this.id;
}).get()
}
Working Demo
For hiding elements that do not have data-title value equal to:
$('.listItem[data-title!="'+filterItem+'"]').hide()
Using Jquery, you can do the following:
var arr = [];
$('.listItem').each(function(){
arr.push($(this).attr('id'));
});
Using jQuery .each():
var arr = [];
$('.listItem').each(function(){
arr.push(this.id);
});
Using jQuery .map()
var arr = $('.listItem').map(function() { return this.id; }).get();
I modified your fiddle example. see this updated fiddle
$("#filter").click(function () {
var filterItem = "A03-5(KAB製ヒーター付エアサスオペシート)_20140515154904.xlsx";
FilterFiles(filterItem);
});
function FilterFiles(filterItem) {
var elements = $("div.listItem");
elements.each(function(){
var el=$(this);
if(el.data("title")!=filterItem)
el.hide();
else
el.show();
});
/*for (var i = 0; i < elements.length; i++) {
alert(elements[i].id);
// get div id of divs with data-title !=(not equal) filterItem
// make display:none of matching divs
}*/
}

Jquery to check height and add class

I am trying to check which div has bigger height and than place a class inside the one that is greater.
I have this code
$(document).ready(function () {
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (sideNavMenu > mainColumn)
{
$(".col-md-3").addClass('dotRight');
}
else
{
$(".col-md-9").addClass('dotLeft');
}
});
The goal here is to check if sideNavMenu is greater than mainColumn than place dotRight on its div tag.
If the mainColumn is greater, then place dotLeft on its div tag.
But its not working.
Any suggestion how to change/improve it.
Thanks a lot
You should reference these by IDs and not classes, since there can be multiple elements with these class names on the page. There should only be one with each ID.
$(document).ready(function () {
var sideNavMenu = $("#sidebar").height();
var mainColumn = $("#main").height();
if (sideNavMenu > mainColumn) {
$("#sidebar").addClass('dotRight');
} else {
$(".#main").addClass('dotLeft');
}
});
Of course, you need to add the id's to your <div>s respectively.
The jQuery docs say:
Get the current computed height for the first element in the set of matched elements or set the height of every matched element.
But, I was just playing with it in jsfiddle and it seems to return an object containing the height of the first element.
http://jsfiddle.net/wwx2m/2/
Which means you should be able to do:
$(document).ready(function () {
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (JSON.stringify(sideNavMenu) > JSON.stringify(mainColumn)) {
$(".col-md-3").addClass('dotRight');
} else {
$(".col-md-9").addClass('dotLeft');
}
});
But the first way I said is preferred. This is not stable, since there can be more objects introduced with the same class. The only reason I'm even mentioning it is to explain why you were having problems with your original code. :)
http://jsfiddle.net/wwx2m/4/
I put the jsfiddle together for you
<html>
<div class='col-md-3'>
</div>
<div class='col-md-9'>
</div>
<script>
var sideNavMenu = $(".col-md-3").height();
var mainColumn = $(".col-md-9").height();
if (sideNavMenu > mainColumn){
$(".col-md-3").addClass('dotRight');
}
else{
$(".col-md-9").addClass('dotLeft');
}
jsFiddle
updated jsFiddle with Animation

How to use arrays in javascript to match up divs when event fires?

I have a set of two divs - First set: when people mouse over these divs, it will fire an event, Second set: when the event is fired, these divs will be displayed.
When you mouse over a div in the first set, it should display its corresponding div in the second set. I thought an easy way to match the mouseover divs with the correct div to display would be using arrays. I've been able attach the event listeners properly, but I can't figure out how to set it up so that when you mouseover one object of an array, it displays the array object with the same index number. I think if I could figure out how to recoginze the index number of the object I am mousing over, I could get it to work. I've tried a lot of things, but haven't been able to create anything that works. Here's the code:
<script>
$(document).ready(function(){
//create array of divs to mouse over
var ar = new Array();
ar[0] = $("#home");
ar[1] = $("#doc");
var length = ar.length;
//create array of divs to display when event is fired
var des = new Array();
des[0] = $("#homeDes");
des[1] = $("#docDes");
// start for
for ( var i = 0; i< length; ++i )
{
ar[i].bind("mouseover",function(){$(des[i]).css("display","block");});
ar[i].bind("mouseout",function(){$(des[i]).css("display","none");});
}
//end for
});
//end
</script>
I would tend toward making a more flexible approach to this so that you don't need to change your javascript when you change your HTML. Consider classing your elements that need to have the bindings and providing data attribute to specify the target. Your HTML for divs to be bound might look like this:
<div id="home" class="mouseoverToggleTrigger" data-target="#homeDes">...</div>
And the jQuery might look like this:
$(document).ready(function(){
$('.mouseoverToggleTrigger').hover(function() {
var $target = $($(this).data('target'));
$target.toggle();
}
});
Note this is assuming you are using HTML5 for which jQuery, by default, converts data-* into values retrievable via data().
For pages that are not HTML5, this more generalized solution will work
$(document).ready(function(){
$('.mouseoverToggleTrigger').hover(function() {
var $target = $($(this).prop('data-target'));
$target.toggle();
}
});
One additional bit of flexibility this gives, is that you now don't have to limit yourself to a one-to-one trigger to target mapping. You could specify a class name or other jQuery selector for data-target values to get highly customized behavior, such as one trigger toggling all elements of a certain class that are children of another class.
$(document).ready(function(){
//create array of divs to mouse over
var ar = new Array();
ar[0] = $("#home");
ar[1] = $("#doc");
var length = ar.length;
//create array of divs to display when event is fired
var des = new Array();
des[0] = $("#homeDes");
des[1] = $("#docDes");
// start for
for ( var i = 0; i< length; ++i )
{
// WRAP THE BODY OF THE FOR LOOP IN A FUNCTION
function(index) {
ar[index].bind("mouseover",function() {
$(des[index]).css("display","block");}
);
ar[index].bind("mouseout",function() {
$(des[index]).css("display","none");
});
}(i);
}
//end for
});
When the events are fired the value of i is the length of the array, you have to pass the value of i to another function so that in each function scope the value of index will be the value of i when it was called.
A simpler approach code wise is to give the common elements common classes and then use jQuery index() and eq() to match pairings
HTML
<a id="home" class="hoverMe">
<a id="doc" class="hoverMe">
<div id="homeDes" class="content">
<div id="docDes" class="content">
JS
var $content=$('.content')
var $links=$('.hoverMe').hover(function(){
$content.eq( $links.index(this) ).show()
},function(){
$content.eq( $links.index(this) ).hide()
})
index() API Docs
eq() API Docs

Add new item to bottom of scrollabe div

I'm trying to append a div to the bottom of a another div, by clicking a button in javascript, but once the height of the outer container is reached, it no longer scrolls the list to the bottom, after an insert.
Please see the fiddle here
If you click the red add button until you get to about 13 items in the list, it seems something goes wrong with the scrollTop function, and it it no longer functions correctly (hovers around the same spot in).
I'm pretty lost on this, and have tried a bunch of different combinations of css settings for both the container and side div. Please help me.
I've reformatted your code to be more jQuery-esque. The main change, however, was to change the list.scrollTop() function so that it just scrolls to the bottom of list:
$(document).ready(function() {
var list = $("#q-d-list");
$(document).on('click', '#add', function() {
$('.active', list).removeClass("active");
var count = list.children().length + 1;
var active = $('<div />', {
'data-qid': count,
'class': 'mli active'
}).text('q' + count).appendTo(list);
list.scrollTop(list[0].scrollHeight);
});
});​
Demo: http://jsfiddle.net/MrvcB/19/
Use
list.scrollTop(list.get(0).scrollHeight);
rather than
list.scrollTop($(".active").offset().top);
Try:
$(document).ready(function () {
var count = 2;
$("#add").live("click", function () {
var list= $("#q-d-list");
// remove the active class from the old item
var $clone = $(list.find("div:last-child").removeClass("active").clone());
count+=1;
var str_count = "q"+count.toString();
$clone.addClass("active").attr("data-qid",str_count).text(str_count);
list.append($clone);
list.scrollTop(list.get(0).scrollHeight);
});
});
http://jsfiddle.net/H4Kb3/

Categories

Resources