Showing/Hiding Divs with the same class name - Javascript - javascript

I am trying to replicate something similar to what the Google Javascript from the Ground up Accomplishes
http://code.google.com/edu/submissions/html-css-javascript/#javascript
Basically have multiple div classes with the same name and show/hide those based on adding removing classes to the original class name.
Heres my markup
<div class="vidItem" id="vidItem">
<div class="vidTitle">
<h2></h2>
</div>
<div class="vidContain" id="vidContain">
<iframe class="testtt" width="560" height="315" src="-----" frameborder="0" allowfullscreen> </iframe>
</div>
</div>
<div class="vidItem" id="vidItem">
<div class="vidTitle">
<h2></h2>
</div>
<div class="vidContain" id="vidContain">
<iframe width="560" height="315" src="----" frameborder="0" allowfullscreen></iframe>
</div>
</div>
Heres my javascript
var toggleExpando = function() {
var expando = this.parentNode;
if (hasClass(expando, 'hide')) {
removeClass(expando, 'hide');
addClass(expando, 'show');
} else {
removeClass(expando, 'show');
addClass(expando, 'hide');
}
};
var expandos = getElementsByClass('vidContain');
for (var i=0; i < expandos.length; i++) {
addClass(expandos[i], 'hide');
var expandoTitle = document.getElementById('vidItem');
addEventSimple(expandoTitle, 'click', toggleExpando);
}
}
Onload both of the divs seem to set their classes to hide just fine but when I click on the top one everything disappears but when I click on the bottom one nothing happens. I am assuming there is a problem with my for loop and also where it says (expando = this.parentNode). I have no idea where to go from here.
Any help or ideas would be appreciated.

Javascript assumes that there is only one element with specific id (and this is what standard say). So when you say..
var expandoTitle = document.getElementById('vidItem');
here the variable contains only first item with id vidItem and attaches event to that element only.
This can be corrected by using class names instead of id.

jQuery might be a good option for this. ID needs to be unique but classes don't, so you can query for all element with a class name in the same way you would with id's in straight javascript by using jQuery. Not sure on what you want the initial state to be so i'm hiding all on inital load. Something along the lines of below is what i mean. (code is untested. place it in the html head)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.vidItem').addClass('hide');
$('.vidItem').click(function(){
$('.vidItem').addClass('hide');
$(this).removeClass('hide');
$(this).addClass('show');
});
});
</script>
If you want to make it look nice with transition effects you can use some of the build in jQuery ones such as:
$('.vidItem').fadeOut();
$(this).fadeIn();
or
$('.vidItem').slideUp();
$(this).slideDown();

Related

If div in iframe has child with specific class do

I want to add a class to the parent if the child has a specific class.
The problem: It's in an iFrame and I'm not very good with jQuery. It don't really has to be jQuery, any other way would be also great. Just notice: The iFrame is on my domain, but I can't access it, because it's generated by a plugin.
If you have any ideas how to fix it, I would appreciate it
My HTML looks somewhat like this in devtools:
<iframe src="#" id="iFrameResizer0">
<div class="book-day">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
</iframe>
and my jQuery:
$(document).ready(function () {
$("#iFrameResizer0").contents().find(".book-day button")
if ($('.book-day button').hasClass('disabled')) {
$(".book-day button").parent().addClass('disabled');
}
});
if everything works correct I want my html looks like this afterwards:
<iframe src="#" id="iFrameResizer0">
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
</iframe>
Devtools:
NOTE: this code has to be executed AFTER the iFrame has loaded and rendered. If you execute this in the head of the parent page without wrapping it in $(function() { ... }), it will not work
You have more than one book-day, you will need to loop:
$("#iFrameResizer0").contents().find(".book-day button").each(function() {
$(this).parent().toggleClass('disabled',$(this).is('.disabled'));
})
or perhaps
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().addClass('disabled');
})
PS: To remove them you do not need to give them a class:
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().remove;
})
If you still have issue with the timing, try this script right after the iframe tags - right after the </iframe>
<script>
$("#iFrameResizer0").on("load",function() {
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().remove(); // or .addClass('disabled');
})
})
</script>
UPDATE: Alternatively drop the iFrame completely:
Replace the iframe tags with <div id="iFrameResizer0"></div>
and add
<script>
$("#iFrameResizer0").load("/wp-json/ssa/v1/embed-inner?integration.../type/Reservierung",function() {
$("#iFrameResizer0").find(".book-day button.disabled").each(function() {
$(this).parent().remove(); // or .addClass('disabled');
});
});
</script>
Example pretending your iframe.content() works as expected (same origin)
$(function() { // on page load. This might STILL be too early
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().addClass('disabled');
})
});
.disabled {
background-color: grey
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="iFrameResizer0">
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
</div>
You don't have to check for every button if it has disabled class or not. You can directly select those button having disabled class.
In Javascript, you have to iterate for all the buttons having disabled class, and add disabled class to it's parent. However, in jQuery, as you can see, you can achieve that, without using any loop.
For JavaScript :
$(document).ready(function() {
var all = document.querySelectorAll('#iFrameResizer0 .book-day button.disabled');
all.forEach((item) => {
item.parentElement.classList.add('disabled');
})
});
For jQuery :
$("#iFrameResizer0 .book-day button.disabled").parent().addClass('disabled');
Since the iframe is observing same-origin policy, This is possible.
First you need to select your iframe element using the following JS
var iframe = document.getElementById('iFrameResizer0');
Now you need to get the content in your iframe
var iframeContent = iframe.contentDocument;
Then select elements inside your Iframe which you wish to modify
var iframeElement = iframeContent.getElementsByClassName("book-day");
var i = 0, ilen = iframeElement.length - 1;
for (var i = 0; i < ilen; i++) {
var button = iframeElement.getElementsByTagName("button");
if(button.className == 'disabled')
{
iframeElement[i].className == 'disabled';
}
}
Then hide your element using CSS display:none property
.disabled {display:none;}

change display of element with class x by clicking element with class y (JS)

Using JS or Jquery (preferred JS) how can I change the display style of an element after clicking on another element (both elements identified by their respective classes).
The below doesnt seem to work.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<i id="xyz" class="class1" >hey</i>
<div id="abc" class="class2" style="display: block;">lo</div>
<script type="text/javascript>
$(function() {
$(".xyz").click(function() {
console.log("element with class xyz was clicked");
$(".abc").css('display': 'none');
});
});
</script>
the console doesnt even log anything
It looks like you are trying to reference your IDs by using CLASS syntax in your jQuery selector.
Instead of using $(".xyz") use $("#xyz"). Same for your $(".abc") selector.
Hope that helps!
You should use document.querySelector(cssSelector) for getting elements by class or id or document.getElementById to get elements by id only.
Here is VanilaJS solution:
var firstElem = document.querySelector(".class1");
firstElem.addEventListener("click", function(event){
var secondElem = document.querySelector(".class2");
secondElem.style.display = "none";
})
<i id="xyz" class="class1" >hey</i>
<div id="abc" class="class2">lo</div>

Simple toggle div visibility with Javascript not working

This is very frustrating as it seems so simple yet is not working.
In my body I have
<div id ="splashscreen" style="display:block">
<h3>title</h3>
<p>text</p>
<inputtype="button" value="Start" onClick="splash();" />
</div>`
And in my head, within script tags I have
function splash() {
var divSplash = document.getElementById("splashscreen");
divSplash.style.display = "none";
}
Surely when Start button is clicked, the splash() function should be called and the display of my splashscreen div be chanted to none?
The problem here is that the you write language="text/javascript", if you use instead language="javascript" it works.
I recommend you remove the language property and use type="text/javascript" instead. If you're using HTML5, you can omit the type property.
<script type="text/javascript">
function startGame() {
var divSplash = document.getElementById("splash");
divSplash.style.display = "none";
}
</script>
Also, the language property is now obsolete.
Using the exact code that you show here, I get the error 'divSplash is null.' This is to be expected -- your div is named "spashscreen" but your JS function is looking for a div named "splashscreen." (You're missing an 'l').
When I fix the typo, it works.
You're not using the same id :)
spashscreen != splashscreen
Here is the answer in a jsfiddle
HTML:
<div id ="splashscreen" style="display:block">
<h3>title</h3>
<p>text</p>
<button onclick="splash()">Start</button>
</div>
Javascript:
function splash() {
var divSplash = document.getElementById('splashscreen');
divSplash.style.display = "none";
}

Javascript Hover Content Show

I am attempting to write a JS function (using prototype in rails) that will show hidden divs within a li when that li is mouseover'ed. Each li has a unique id that is a number, like so:
<li id="100">
<div style="display:none;" id="hover-display-content">Content</div>
<div style="display:none;" id="more-hover-display-content">Content</div>
<div style="display:none;" id="even-more-hover-display-content">Content</div>
</li>
I'm not sure how to go about doing this though, especially where the JS only shows the hidden elemenst for that specific li.
I'm thinking something like:
Event.observe(window, 'load', function() {
Event.observe($("li"), 'mouseover', function() {
var id = readAttribute("id")
id.getElementById("hover-display-content").style.display = "inline";
id.getElementById("more-hover-display-content").style.display = "inline";
id.getElementById("even-hover-display-content").style.display = "inline";
});
Event.observe($("li"), 'mouseout', function() {
var id = readAttribute("id")
id.getElementById("hover-display-content").style.display = "none";
id.getElementById("more-hover-display-content").style.display = "none";
id.getElementById("even-hover-display-content").style.display = "none";
});
});
But it doesn't seem to be working. Where am I going wrong?
Edit:
I am now using:
Event.observe(window, 'load', function() {
$$('li').invoke('observe', 'mouseover', function(event) {
this.children[0].toggle();
});
$$('li').invoke('observe', 'mouseout', function(event) {
document.children[0].toggle();
});
});
Which is partially working, however my code looks like the following:
<ul>
<li>
<div style="display:hidden;">Hidden Div</div>
<div>More content that isn't hidden</div>
</li>
</ul>
When I rollover the li it displays the hidden div, however if I rollover the second div it hides the comment again, even though this div is in the li. Why?
with a tag and hover? just providing an idea
<html>
<head>
<style>
a div{display:none; height:10px;}
a:hover div{display:inline;}
</style>
</head>
<body>
<ul>
<li><a>a<div id="hover-display-content">Content</div></a></li>
<li><a>s<div id="more-hover-display-content">Content1</div></a></li>
<li><a>d<div id="even-more-hover-display-content">Content2</div></a></li>
</ul>
</body>
</html>
Im not sure if this is your only issue but one key thing is that DOM id's cannot begin with a number, youll need to prefix that with something like model_name-100. Additionally, all id's need to be unique. So your inner content div's need to have those id's converted to classes like class="even-more-hover-display-content"... or alternatively you could jsut prefix the id with the id of the parent element like model_name-100-even-more-hover-display-content.
I would start with the .getElementByClass() --- deprecated in Proto 1.6
Link here.
As a fallback plan, here's a proof-of-concept in regular JS that works:
<li onmouseover="this.children[0].style.display = 'inline';
this.children[1].style.display = 'inline';">
<div id="testdiv" style="display:none;background:blue">test</div>
<div id="testdiv" style="display:none;background:blue">test</div>
</li>
using jquery
$('#id').each(function(){
$(this).css({diplay:'inline'});});
isn't that simple . .

Javascript creating <div> on the fly

I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

Categories