how to economize jquery selectors - javascript

Probably a stupid question, but I couldn't find a direct answer, so how can I change ":not('#home div, .nav')" in to something like ":not('this div, .nav')"? That would allow me reuse the same function for different objects.
$( "#home" ).click(function() {
$("#content .plates").children(":not('#home div, .nav')" ).fadeOut(700);
});
and here is the HTML if needed:
<div id="wrapper">
<div id="content">
<div id="home" class="plates">
<div class="nav"></div>
<div id="one"></div>
<div id="two"></div>
</div>
<div id="about" class="plates">
<div class="nav"></div>
<div id="three"></div>
<div id="four"></div>
</div>
</div>
</div>
Thanks for your help!

In the handler, this will be the clicked element, so you could just use this:
$( "#home" ).click(function() {
$("#wrapper #content .plates").children(":not('#"+this.id+" div, .nav')" ).fadeOut(700);
});

The OP is asking for something generic that can be reused on both the "home" and the "about" divs (and maybe on others to be added later?). But, for each one, excluding the "nav" item from the fadeout. So try this:
function myFunc( clickableItem) {
$(".plates:not(" + clickableItem + ")").children( ":not('.nav')" ).fadeOut(700); }
$( "#home" ).click( function(){
myFunc( "#home");
});
$( "#about" ).click( function(){
myFunc("#about");
});

You are using CSS selector :not(), but you can also use jQuery chained function .not(), which subtracts matched elements from another set of matched elements.
The usage is like this:
$(selector1).not(selector2).fadeOut(700);
Where elements in selector2 will get substracted from set matched by selector1.

Let's start from the top. Provided you follow the spec and IDs are unique on your page (as they should be), your click event selector should be just
$("#home").click(function() {...});
Also, the inner selector should be
$("#content .plates").children(...);
There's no need to stack ID selectors in front of other ID selectors since IDs should be unique and selectors are parsed from right to left.

You can use jQuery not to exclude the clicked element.
Code:
$("#wrapper #content #home").click(function () {
$("#wrapper #content .plates").children(':not(.nav)').not($(this)).fadeOut(700);
});
Demo: http://jsfiddle.net/IrvinDominin/dms6u1ww/

$("#wrapper #content #home" ).click(function() {
$("#wrapper #content .plates").children().not($('div', this)).not('.nav').fadeOut(700);
});

Related

How to make a re-usable element with $(this) triggers the clicked element only

I'm trying to make my JS logic to use the $(this) so I can re-use my code in multiple elements in the same page so that they are each triggered individually.
this is my JS code:
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(".screen2").addClass("active");
$(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(".screen2").removeClass("active");
$(".fab").removeClass("clicked");
$(".box1 ,.box2 ,.box3").removeClass("active");
});
My HTML:
<div class="app">
<div class="header"></div>
<div class="content">
<h1>Click the fab</h1>
</div>
<div class="fab"></div>
<div class="screen2">
<h1>new window</h1>
<div id="close"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</div>
how can I use properly the $(this) ? All I'm trying to do is to make that JS code re-usable for multiple elements in the same page so that it triggers ONLY for the element where I clicked the .fab button...
You also need to use $(this), .prev(), .next(), .find(), .closest() etc. to traverse the DOM to refer to the elements near the one you're working on, otherwise it will target all of the classes in your document.
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(this).next(".screen2").addClass("active");
$(this).next(".screen2").find(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(this).closest(".screen2").removeClass("active");
$(this).closest(".screen2").prev(".fab").removeClass("clicked");
$(this).closest(".screen2").find(".box1 ,.box2 ,.box3").removeClass("active");
});
You can store the jQuery selectors in an array, iterate through it, and for each jQuery selector in the array, use jQuery's .each() to iterate through its inner elements.
In the following example, there may be multiple instances of class1 in the DOM, for example.
var arrElements = [$('#id1'), $('#id2'), $('.class1')];
for (var i = 0; i < arrElements.length; i++) {
arrElements[i].each(function() {
$(this).on('click', function() {
// do stuff (use $(this) to refer to the current object)
});
})
}

jquery slideToggle opens all divs instead of just the div that is required

I have a page that can have a variable number of <div> the idea is people can click the + symbol which is an <img> then the div that is linked to the img tag will display.
I currently have:
PHP/HTML
$plus = '<img src="images/plus.png" class="clickme" width="20px" height="20px">';
$table .= '<div>'.$plus.'</div>';
$hidden .= '<div class"diary">-Content-</div>';
JS
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$( ".clickme" ).click(function() {
$( ".diary" ).slideToggle( "slow", function() {
});
});
});
</script>
This obviously opens all divs and not just the one that is clicked on. I have looked at other similar questions on here and have tried a number of variations such as:
$(document).ready(function(){
$(".clickme").click(function(){
$(this).next(".diary").toggle();
});
});
However, when I try these it just stops working altogether. i.e. none of the divs slide up or down. I see the examples work on JS Fiddle but as soon as i apply it to my page I get nothing.
I am possibly doing something really dumb for it not to work but can't see what.
thanks for any help.
The HTML output should look like
<div>
<div>
<table>
<img class="clickme">
</table>
</div>
<div class="diary">
<table> content </table>
</div>
<div>
(based on tht HTML provided)
Best way would be to add an attribute with matching indexes to both elements
<div>test toggle
<div class="clickme" data-index="1">click me</div>
<div class="toggle" id="obj_1">toggled field</div>
</div>
and then in the JQuery:
$(function () {
$(".clickme").click(function () {
//get number from clicked element's attribute
var index =$(this).attr('data-index');
//select element with id that matches index and toggle
$('#obj_'+index).toggle();
});
})
After looking at your code, i can see that the slideToggle call is maded on .diary class which is probably applied on each of your elements.
I suggest you to put your diary div inside the $plus div then use jquery children or simply give your .diary divs a unique id and use the id attribute for your
toggle.
EDIT:
Here is a simple html output:
<div class="clickme">
<div class="diary">CONTENT HERE</div>
</div>
Add this in the CSS:
.clickme {
background: url('images/plus.png') no-repeat top left;
min-width: 20px;
min-height: 20px;
cursor: pointer;
}
Script tag:
<script>
$(function() {
$(".clickme").click(function() {
$(this).children().slideToggle("slow");
});
});
</script>
Note that i'd let the diary class for your usage and styling purpose but it's not used anywhere.

How to insert a div after another jquery

I have a div in html page:
<div id="home">
</div>
Now I want to put another div under the div with id=home. I mean under the other div:
<div id="home">
</div>
<div id="new">
</div>
This is my jquery code:
var div=$('div');
var sopra=$('#home');
sopra.append(div);
But this code is wrong because put the new div in the div with id=home.
Anyone can help me?
You could use .after() function :
var div=$('<div id="new">new</div>');
var sopra=$('#home');
$( sopra ).after( div );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="home">home
</div>
Or also using .insertAfter() function :
var div=$('<div id="new">new</div>');
var sopra=$('#home');
$( div ).insertAfter( sopra );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="home">home</div>
The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.
Hope this helps.
Pure JavaScript:
You can do it using insertAdjacentHTML() method:
document.getElementById('home').insertAdjacentHTML('afterend', '<div id="new"></div>');
afterend means after closing </div> tag.
Snippet:
document.getElementById('home').insertAdjacentHTML('afterend', '<div id="new">new</div>');
<div id="home">home</div>

Show content only from the clicked link and hide all siblings

as stated in the name, i have a menu with links, and i have a list of sections which i want to show/hide on the click of the menu.
What i want here is to be dynamic in a sense that if i add more menus and sections I don't have to change the code that does it, or to add new tags or names.
I tried doing something myself but I'm probably missing something..
Any assistance would be appriciated
I have a simple example on this jfiddle: https://jsfiddle.net/s07ysx6w/6/
HTML:
<div id="header">
<div id="menuBlock">
<ul id="menu">
<li>Novosti</li>
<li>Program Mladi</li>
<li>Program Odrasli</li>
<li>Program Upisi</li>
<li>Galerija</li>
<li>Kontakt</li>
</ul>
</div>
</div>
<body>
<div id="main">
<div id="novosti" name="sekcija1" class="sekcija">
aaaa
</div>
<div id="programMladi" name="sekcija2" class="sekcija">
aaaa
</div>
<div id="programOdrasli" name="sekcija3" class="sekcija">
aaaa
</div>
<div id="programUpisi" name="sekcija4" class="sekcija">
aaa
</div>
<div id="galerija" name="sekcija5" class="sekcija">
aaaa
</div>
<div id="kontakt" name="sekcija6" class="sekcija">
aaa
</div>
</div>
</body>
Javascript:
$(document).ready(function() {
$("#menu").click(function(e) {
var selected = this.attr('href');
$('#main' + selected).show('slow').siblings().hide('slow');
});
});
EDITED:
Copy/pasting made me careless so now there are only unique id's. Also replaced the fiddle with a working one (solution).
UPDATE:
In case anyone uses slicknav as a plugin on his/her's page, to get to the element you have in your menu you need to find how exactly slicknav injected it into your page. For instance, in my case, since i prepend it to my #menuBlock div tag. In order to find the element #novosti i had to dig in deep, since slicknav creates tags on its own in order to work the way it does.
In that case my javascript looked like this.
$(document).ready(function(){
$("#menuBlock div ul li a").click(function (e){
e.preventDefault();
var selected = $(this).attr('href');
$( selected ).fadeIn('slow').siblings().hide();
});
});
There should a space between 2 selectors if they have a parent child relationship, so change this line
$('#main' + selected).show('slow').siblings().hide('slow');
to
$('#main ' + selected).show('slow').siblings().hide('slow');
or simply the selected one (since it is already pointing to a specific element)
$(selected).show('slow').siblings().hide('slow');
check this updated fiddle
$(document).ready(function(){
$("#menu li a").click(function (e){ //bind the event on `a` rather than ul
var selected = $(this).attr('href'); //use $(this) instead of this
$( selected ).show('slow').siblings().hide('slow'); //explained above
});
});
There are more than one errors found in your code,
set a Jquery library
Id should be unique throughout the DOM
Replace this.attr with $(this).attr()
Descendant selector would be #menu #something not #menu#something
Should .stop() an animation before beginning the new one.
Try,
$(document).ready(function() {
$("#menu li a").click(function(e) {
e.preventDefault()
var selected = $(this).attr('href');
$('#main ' + selected).stop().show('slow').siblings().hide('slow');
});
});
DEMO
Try this method
$(document).ready(function() {
$("#menu a").click(function(e) {
debugger;
var selected = $(this).attr('name');
$('#main div').hide();
$('#main div[name="'+selected+'"]').show('slow');
});
});
You are not supposed to have more than one element with the same ID on a page, so change the id on the page to something more specific. Or I'm I mistaken? From your question, you wanted something more extensible, here is an approach
$(document).ready(function(){
$("#menu").click(function (e){
var element = $(e.target).attr('href');
$('#main-divs > ' + element).show('slow').siblings().hide('slow');
});
});

How to target a div by class name inside another class

I have some divs like this.
<div class"parent">
<div class"child">
Some Stuff Here
</div>
</div>
<div class"parent">
<div class"child">
Some other kinda Stuff Here
</div>
</div>
I want to click parent class and show the child class only inside that parent without showing the other children classes in other parent classes.
$(document).on('click', '.parent', function(){
$(this).find($('.child').show(500));
});
Pass a selector string to find() not an object - you are passing a jQuery object. You also have invalid HTML because class"parent" should be class="parent".
Demo
$(document).on('click', '.parent', function(){
$(this).find('.child').show(500);
});
First of all you need to correct your markup as there should be = between attribute class and its value. So markup should be like :
<div class="parent">
<div class="child" >
Some Stuff Here
</div>
</div>
Try this :
$(document).on('click', '.parent', function(){
$(this).children('.child').show(500);
});
Demo
You need to correct the HTML as
<div class="child">
'=' is missing in your markup
The following line is enough:
$(document).on('click', '.parent', function(){
$(this).find('.child').show(500);
});
Do no use selector $('.child') in find, as it will return all the child in DOM and find , $(this).find($('.child').show(500)); should be $(this).find('.child').show(500);
Also correct the html, class"parent" should be class="parent", same applies to class"child"
Live Demo
$(document).on('click', '.parent', function(){
$(this).find('.child').show(500);
});

Categories

Resources