Trying to traverse the DOM so unique video will play when certain div is clicked - javascript

So, I have a requirement for dynamically generated content blocks on a page. These blocks have a thumbnail and when it is clicked, it should open a modal, and display an unique overlay window, as well as as the unique associated video.
I am trying to write some generic JavaScript that will traverse the DOM tree properly, so that when any particular thumbnail is clicked, a modal, the associated overlay, and the associated video will open.
Here is an example of what I have now (there are many of these, dynamically added):
<div class="block">
<div class="thumbnail">
//Thumbnail image
</div>
<p>Video Description</p>
<div class="window hide">
<div class="video hide">
//Video content
</div>
</div>
</div>
<div id="modal" class="hide"></div>
and after attempting to do a bunch of different things, I ended up trying to do something like this for the JavaScript, which doesn't work:
$(".thumbnail").on("click",function(){
$("#modal").removeClass("hide").addClass("show");
$(this).closest(".window").removeClass("hide").addClass("show");
$(this).closest(".video").removeClass("hide").addClass("show");
});
CSS is very basic:
.hide { display: none; }
.show { display: block; }
Trying to make the click function generic as possible so it would work on any .thumbnail that was clicked. I've also interchanged find(".window") and children(".window") but nothing happens. Any ideas on what I'm doing wrong? Thanks!

Depending on what you actually want your classes to be, I'd use this code:
$(".thumbnail").on("click", function () {
var $block = $(this).closest(".block");
$block.find(".window, .video").add("#modal").removeClass("hide").addClass("show");
});
DEMO: http://jsfiddle.net/gLMSF/ (using different, yet similar code)
It actually finds the right elements, based on the clicked .thumbnail. It finds its containing .block element, then looks at its descendants to find the .window and .video elements.
If you actually want to include . in your attributes, you need to escape them for jQuery selection.
As for styling, you should probably just have the styling be display: block; by default, and then toggle the hide class. It's less work, and makes more sense logically.

You have a huge issue with your class names in HTML:
<div class=".block">
it should be
<div class="block">
Your modal is the only one that has the class properly named. Your DOM traversals will not work because they are looking for "block" but it's called ".block"
So fix it all to this and you should find more success:
<div class="block">
<div class="thumbnail">
//Thumbnail image
</div>
<p>Video Description</p>
<div class="window hide">
<div class="video hide">
//Video content
</div>
</div>
</div>
<div id="modal" class="hide"></div>

Your code won't work because your selectors have periods (.) in your classes if that's actually what you want, you should try it like this:
$(".\\.thumbnail").on("click",function(){
$("#modal").removeClass("hide").addClass("show");
$(this).closest("\\.window").removeClass("hide").addClass("show");
$(this).closest("\\.video").removeClass("hide").addClass("show");
});
Otherwise just try removing the periods from the classes...
Also, you're using .closest() incorrectly, as it looks up through ancestors in the DOM tree...
You should change your code to:
$(".\\.thumbnail").on("click",function(){
$(this).next("\\.window").children(".video")
.addBack().add("#modal").removeClass("hide").addClass("show");
});

Related

using document.querySelector with complex CSS selectors

In JavaScript I want to use document.querySelector to "grab" the last div (<div class="widget-footer">) in below HTML. However after many tries, I still can't figure out the correct CSS selector syntax to use.
The following code does not work:
document.querySelector (".skin-grid-widgets.ui-sortable.gridWidgetTemplatePositie.AgendaStandaard.disablesorting.hoogte-1-knoppen-0.breedte-1.widget-footer")
Here is the HTML I am working with
<div class="skin-grid enkeleKolom" id="Infobalk">
<div class="skin-grid-widgets ui-sortable">
<div class="gridWidgetTemplatePositie AgendaStandaard disablesorting hoogte-1-knoppen-0 breedte-1">
<div class="widget-header">
here comes the header text
</div>
<div class="widget-body">
some body text
</div>
<div class="widget-footer">
here comes the footer text
</div>
</div>
</div>
</div>
I've surfed everywhere to find example of complex CSS selectors used with querySelector, but to no avail. Any help would be really appreciated.
Your issue is you need a space in between each child element you are trying to select. If you do not have spaces in between your class selectors, by CSS specification, it will look for both classes on the same element.
Change your selector to look like the following:
var footer = document.querySelector(".skin-grid-widgets.ui-sortable .gridWidgetTemplatePositie.AgendaStandaard.disablesorting.hoogte-1-knoppen-0.breedte-1 .widget-footer");
footer.classList.add("highlight");
.highlight {
background-color: yellow;
}
<div class="skin-grid enkeleKolom" id="Infobalk">
<div class="skin-grid-widgets ui-sortable">
<div class="gridWidgetTemplatePositie AgendaStandaard disablesorting hoogte-1-knoppen-0 breedte-1">
<div class="widget-header">
here comes the header text
</div>
<div class="widget-body">
some body text
</div>
<div class="widget-footer">
here comes the footer text
</div>
</div>
</div>
</div>
try this:
<script>
document.querySelector (".skin-grid-widgets .gridWidgetTemplatePositie .widget-footer");
</script>
You don't need to add adjacent classes like "skin-grid-widgets ui-sortable" in querySelector, if you do so then query selector assumes that "skin-grid-widgets" is parent of "ui-sortable". Use just one of the classes at one DOM level.
The selector ain't complex, your thoughts are.
Listen to yourself, to the description you provide of what you want to select:
"grab" the last div in below HTML
Not grab the node with the class widget-footer inside of a node that has all these classes: gridWidgetTemplatePositie AgendaStandaard disablesorting hoogte-1-knoppen-0 breedte-1, inside a node ...
//a utility, because DRY.
//and because it's nicer to work with Arrays than with NodeLists or HTMLCollections.
function $$(selector, ctx=document){
return Array.from(ctx.querySelectorAll(selector));
}
//and the last div in this document:
var target = $$('div').pop();
or
"grab" <div class="widget-footer"> in below HTML
var target = document.querySelector("div.widget-footer");
or the combination: grab the last div.widget-footer in the HTML
var target = $$('div.widget-footer').pop();

Selecting only one div of entire css class in jQuery

my goal is to show an overlay on a div when that div is hovered on. The normal div is called .circleBase.type1 and the overlay is circleBase.overlay. I have multiple of these divs on my page. When I hover over one .cirlceBase.type1, overlays show on every .circleBase.type1. How do I prevent this?
Here is some code:
HTML
<div class="circleBase type1">
<p class="hidetext">Lorem ipsum</p>
<hr size="10">
<strong class="gray hidetext">gdroel</strong>
</div>
<div class="circleBase overlay">
<p class="date">11/12/14</p>
</div>
and jQuery
$(document).ready(function(){
$('.overlay').hide();
$('.date').hide();
$(".circleBase.type1").mouseenter(function(){
$(".overlay").fadeIn("fast");
$('.date').show();
$('.hidetext').hide();
});
$(".overlay").mouseleave(function(){
$(this).fadeOut("fast");
$('.date').hide();
$('.hidetext').show();
});
});
Use $(this) to get current element reference and do like this:
$(".circleBase.type1").mouseenter(function(){
$(this).next(".overlay").fadeIn("fast");
$(this).next(".overlay").find('.date').show();
$(this).find('.hidetext').hide();
});
and:
$(".overlay").mouseleave(function(){
$(this).fadeOut("fast");
$(this).find('.date').hide();
$(this).prev(".circleBase").find('.hidetext').show();
});
usually when I want to target something specific you just give it an ID.
ID's play better in JavaScript than classes.
If you had a specific container, using the container as your starting point is a good route as well
$('#container').find('.something.type1').doSomething();
This is much more efficient for jquery, because it only searches .something.type1 inside of #container.
Well I'm not sure exactly what you're looking to do, but it looks like you want to replace content in some kind of circle with a hover text, but with a fade. To do that you'll have to add some CSS and it would be best to change your HTML structure too.
The HTML should look like this:
<div class="circleContainer">
<div class="circleBase">
<p>Lorem ipsum</p>
<hr>
<strong class="gray">gdroel</strong>
</div>
<div class="overlay" style="display: none;">
<p class="date">11/12/14</p>
</div>
</div>
so your js can look like this:
$(function(){
$(".circleContainer").mouseenter(function(){
$(this).find(".overlay")
$(this).find('.circleBase').hide();
});
$(".circleContainer").mouseleave(function(){
$(this).find('.circleBase').show();
$(this).find(".overlay").hide();
});
});
Here's a working solution that includes some CSS to make it nice. Try taking it out and running it, you'll see the problems right away.

jquery have 2 functions work in succession on click

I have this JS code:
function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
which opens up a new window on click. What I want it to do next from that first click is go to another function. That function entails a scroller that has 5 divs in it. Say I want it to go to the third div or ID, how would I go about writing that type of function? So a HTML example would be:
<div id="this">
<div class="outer">
<div class="innerdiv">
<div class="1" id="1">1</div>
<div class="2" id="2">2</div>
<div class="3" id="3">3</div>
<div class="4" id="4">4</div>
<div class="5" id="5">5</div>
</div>
</div>
</div>
This would represent my scroller. So on that initial first click, the idea is that it would open up a new window and scroll to that 3rd div, or if scrolling to it is to difficult, then go to that first div. http://jsfiddle.net/qYTK4/
<div class="arrowbox">
<div style="display:inline-block; width:155px; height: 50px; float:left;"></div>
<div class="leftbox" id="leftbox"></div>
<div class="backtohome">BACK TO HOME PAGE</div>
<div class="rightbox" id="rightbox"></div>
Using window.scrollTo() and move it to the objects position. Retrieve the position (X,Y) of an HTML element
jQuery.ScrollTo is a great, simple plugin for smooth scrolling animations. It has tons of options for ways to define the scroll behavior and is pretty easy to use. There are a ton of demos and examples on the site linked you should be able to use. In yours you would just tell it to scroll to either the DOM element itself or jQuery object/selector for the 3rd div.
Also, you can't have id attributes start with numbers (like your divs), it's not valid. Classes can but not IDs.
It is also a good idea to rely on click event handlers (i.e. $('.backtohome a').on('click', function() { // your code });) rather than onclick attributes.

Store multiple CSS classes in an array

I'm still pretty new to JQuery and JavaScript as a whole, so bear with me. I tried searching the web for an answer to my question and experimented a little bit, but I'm coming up dry. Anyway, is there a way to store multiple CSS classes in an array with JavaScript?
I'm writing some simple JQuery for a friend's portfolio website such as this:
$('.item.two').click(function(){
$('.content.item, .current.item').show();
$('.content.item, .content.item, .content.item, .current.item, .current.item, .current.item').hide();
$('.item.one, .item.three, .item.four').fadeTo(0, 0.5);
$('.item.two').fadeTo(0, 1.0);
});
All this is doing is hiding certain elements and only showing them when their corresponding icon is clicked on. This is also turning the opacity from 50% off the main class to 100% when clicked on.
There's nothing wrong with the code itself, it serves its intended purpose. But is there a way to clean this code up a bit by just holding those classes into a reusable array? I feel like it should be possible, but I'm not sure how.
Thanks!
EDIT: Sorry, I wasn't clear that I'm actually using 4 different classes to hide or show. So instead of the previous bit it's actually
$('.item.two').click(function(){
// this is the content i want to show on click
$('.content.itemTwo').show();
// this is the content that i want to hide/remain hiding on click
$('.content.itemOne, .content.itemThree, .content.itemFour').hide();
// these are icons representing the content
$('.item.one, .item.three, .item.four').fadeTo(0, 0.5);
$('.item.two').fadeTo(0, 1.0);
});
Also, here is my HTML some of you are requesting. Like I said, what I'm trying to make happen, happens. I just feel like there's a better way of making it happen.
<!-- these are icons representing the written content-->
<div class="item one">
<div class="fs1" aria-hidden="true" data-icon=""></div>
</div>
<div class="item two">
<div class="fs1" aria-hidden="true" data-icon=""></div>
</div>
<div class="item three">
<div class="fs1" aria-hidden="true" data-icon=""></div>
</div>
<div class="item four">
<div class="fs1" aria-hidden="true" data-icon=""></div>
</div>
<!-- this is the written content to be shown upon clicking corresponding icon -->
<div class="content itemOne">
<h3>itemOne</h3>
<p>....</p>
</div>
<div class="content itemTwo">
<h3>itemTwo</h3>
<p>...</p>
<div class="content itemThree">
<h3>itemThree</h3>
<p>...</p>
</div>
<div class="content itemFour">
<h3>itemFour</h3>
<p>....</p>
</div>
Looking at it now, I probably don't need the extra selectors on the .content or .item.
If I correctly understood , you are trying to change the element that is clicked.
$('.item.two').click(function(){
// there is no reason to show and then hide all
$('.content.item, .current.item').hide();
$('.item').not(this).fadeTo(0, 0.5);
$(this).fadeTo(0, 1.0);
});
check if this works for you
Edit another approch could be using index suffix in classes in loop
eg
you could use class1, class2, class3 instead.
$('.item.two').click(function(){
// this is the content i want to show on click
$('.content.itemTwo').show();
// this is the content that i want to hide/remain hiding on click
$('.content.itemOne, .content.itemThree, .content.itemFour').hide();
// these are icons representing the content
$('.item.one, .item.three, .item.four').fadeTo(0, 0.5);
$('.item.two').fadeTo(0, 1.0);
});
to
for(var i=1;i<=4;i++){
$('.item.'+i).click(function(){
// this is the content i want to show on click
$('.content.class'+i).show();
// this is the content that i want to hide/remain hiding on click
$('.content class').hide();
// these are icons representing the content
$('.item').not(this).fadeTo(0, 0.5);
$(this).fadeTo(0, 1.0);
});
}
Hope you can get approch from it
Use the push method like
var arrayClass = [];
$('.item.two').click(function() {
arrayClass.push($(this));
});
alert(arrayClass);
You mean you are trying to select a list of items using jQuery because you have been using a lot of clases? You can do this by using jquery index, with eq and the this selector.
Here is a full description on how to use the index feature to make your code shorter
http://api.jquery.com/index/
You do not have to repeat same class over and over and do not need to store classes in array.
Change
$('.content.item, .content.item, .content.item, .current.item, .current.item, .current.item').hide();
To
$('.content.item').hide();
You can store classes in string instead of array in this case $('.item.one, .item.three, .item.four')
classesSet = ".item.one, .item.three, .item.four";
$(strClassesSet).fadeTo(0, 0.5);

jQuery Simple Collapsible Div?

I am looking for the proper, simple, small code to do the following things:
Click on Element with Class Applied to it.
DIV.CLASS - Which expands and shows hidden content. (slideDown - Toggle)
DIV.CLASS - Which collapses and hides the previously show content. (slideUp - Toggle)
<div class="sitesection">
<p class="expand-one">Click Here To Display The Content <img src="images/arrow.png" width="5" height="7" /></p>
<p class="content-one">This is the content that was hidden before, but now is... Well, visible!"</p>
</div>
So to be vague and easy, I need to know how to get a DIV CLASS to become hidden and visible once an element on the same page has a CLASS applied to it, in which would activate and deactivate the HIDDEN and or VISIBLE HTML Content. And I need it to be hidden by default.
I have looked all over the internet and have only found very complex scripts, but nothing simple. I have found Simple Accordians... But those never close, they just open another one.
$('.expand-one').click(function(){
$('.content-one').slideToggle('slow');
});
Demo: http://jsfiddle.net/Q4PUw/2/
I was looking at this and wanted a collapsible div that was already styled for me. Then I realized what I wanted was a single pane jquery-ui accordion.
<div id="collapse">
<h3>Collapse and Expand</h3>
<div>Content</div>
</div>
<script>
$( "#collapse" ).accordion({
collapsible: true,
active: false
});
</script>
http://jsfiddle.net/MB4ch/1/
I wanted to do this with multiple divs, each with their own trigger. Building on AlienWebguy's answer above:
HTML
<div>
<p class="expand" id="expand-1">more 1...</p>
</div>
<div class="expandable" id="expandable-1">
<p>1. This is the content that was hidden before, but now is... Well, visible!"</p>
</div>
<div>
<p class="expand" id="expand-2">more 2...</p>
</div>
<div class="expandable" id="expandable-2">
<p>2. This is the content that was hidden before, but now is... Well, visible!"</p>
</div>
Javascript
$('.expand').click(function(){
target_num = $(this).attr('id').split('-')[1];
content_id = '#expandable-'.concat(target_num);
$(content_id).slideToggle('fast');
});
CSS
.expand {
font-weight: bold;
font-style: italic;
font-size: 12px;
cursor: pointer;
}
.expandable {
display:none;
}
div {
margin: 10px;
}
https://jsfiddle.net/Q4PUw/3767/
Bad idea to use accordion.
Better is to create your own collapsible block.
Example:
function InitSpoilBlock(idClicked)
{
$(idClicked).on('click', function(e){
var textArray = ['blind','slide'];//here you can add other effects
var randomEffect = textArray[Math.floor(Math.random()*textArray.length)];
$(e.target).parent().children(".HiderPanel").toggle(randomEffect);
});
}
so when you write such html:
<div class="HiderContainer">
More
<div class="HiderPanel">
Spoiled block of html
</div>
</div>
and after page load you will call
InitSpoilBlock('.Hider');
all blocks will be possible to collapse and hide with random animation. Or you can use one exact animation also.

Categories