I am able to change the background-color of this element:
<div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
</div>
But I want to change the color of the first child, which I assumed should work like this:
<div onmouseover="this.firstChild.style.backgroundColor='blue'" onmouseout="this.firstChild.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
<div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>
</div>
But it does not work. What is wrong? How can I change the style of the firstChild?
PS: I later want to use display=block and none and some other propertys (not just style) for the child. The color was just for testing.
As "the system" mentioned, you are targeting a text node rather than an element node. Try using children[0] instead of firstChild.
jFiddle here
You would need to use .firstElementChild, or you'd need to get rid of the formatting whitespace. That whitespace becomes a text node, which is the .firstChild.
The .firstElementChild property isn't supported by some older browsers, so if you're supporting those, you'd need to shim it with a function.
<div onmouseover="changeColor(this, 'blue')" onmouseout="changeColor(this, 'red')" style="background-color:green; width:100px; height:40px;">
<div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>
</div>
function changeColor(el, color) {
firstElemChild(el).style.backgroundColor=color;
}
function firstElemChild(el) {
if (el.firstElementChild)
return el.firstElementChild;
el = el.firstChild
while (el && el.nodeType !== 1)
el = el.nextSibling;
return el;
}
Related
I have a couple of functions, the first replaces the contents of a div the second restores the original div. The problem is because I'm using the replaceWith method, the second div no longer exists if I try to call it a second time. Is there a better way to do this? I've experimented creating a variable that stores the contents of the second div so I can resuse it, but could not get it to work.
The code that I have is:
$(document).ready(function() {
$('#trigger_adults').click(function() {
var mainClone = $("#main-content").clone();
$('#main-content').fadeOut('fast', function() {
$('#main-content').replaceWith($('#adults'));
$('#slider-sec').slideUp('slow');
$('#adults').fadeIn('fast');
$(window).scrollTop(0);
});
$('#return').click(function() {
$("#adults").replaceWith(mainClone.clone());
$('#adults').fadeOut('fast');
$('#slider-sec').slideDown('slow');
});
});
});
Thanks in advance!
You could have both contents in the same div and toggle the visibility of their parent divs. Use javascript just to toggle the wrapper's class.
$('#toggle').click(function() {
$('#wrapper').toggleClass('init-state new-state');
});
#wrapper {
border:1px solid #d8d8d8;
}
.init-state #new,
.new-state #init { display:none; }
.inner {
padding:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="wrapper" class="init-state">
<div id="init" class="inner">Initial Content</div>
<div id="new" class="inner">New Content</div>
<button id="toggle" type="button">Toggle</button>
</div>
From the docs
The .fadeOut() method animates the opacity of the matched elements. Once the opacity reaches 0, the display style property is set to none, so the element no longer affects the layout of the page
you either need to manually set the display style property back to its original value, or call jQuery's .fadeIn() function which will do the opposite of .fadeOut()
I have a page in my application with two hyperlinks. Both of these hyperlinks redirect the user to the same page where they can add information for a new account. When link #1 is selected, one value passed to the controller action must be 1. If the other link is chosen then the value is 2. How can this be done using jquery?
hyperlinks:
<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
ADD CLINIC
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
ADD MEDICAL OFFICE
</div>
Why on Earth do you need to use jQuery for this? Use simple GET parameters.
ADD MEDICAL OFFICE
Note the ?type=1 Passes a get parameter with a value of one.
On the recieving page you can use the folllowing function to check which get parameter was passed.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
Use like this: findGetParameter('type') to get the value of the type from the url.
Got that function from here
just add a GET parameter to the links, they will keep pointing to the same URL but also will pass a parameter
<div style="position:absolute; width:100px; top:25%; left:50%; font-family:Arial; font-weight:bold; white-space:nowrap ">
ADD CLINIC
</div>
<div style="position:absolute; width:100px; top:33%; left:48%; font-family:Arial; font-weight:bold; white-space:nowrap">
ADD MEDICAL OFFICE
</div>
You should define a new attribute like data-id your html element after that detect the click action and change the href.
<div>
<a href="~/rxcard/addaccount" data-id='1'>ADD CLINIC</a>
</div>
<div>
<a href="~/rxcard/addaccount" data-id='2'>ADD MEDICAL OFFICE</a>
</div>
<script>
$("a").on('click',function(){
var thiz = $(this);
thiz.attr('href',thiz.attr('href')+?val=thiz.attr('data-id'));
});
</script>
If you have value in initialization you can give different hrefs your anchors. In this scenario you don't need to Jquery or Javascript;
<div>
ADD CLINIC
</div>
<div>
ADD MEDICAL OFFICE
</div>
I'm trying to get a class added on when a div is inside a certain parent div.
<div class="parent1">
<div class="child">
Content
</div>
</div>
.parent1 only exists on one page, while .child exists on others as well as this one.
So when .child is everywhere else, its color is red, but when it's inside .parent1 I want its color to be blue.
Here's what I'm using.
if ($('.child').parents('.parent1').length == 1) {
.addClass('.new-class');
}
I'm having no success with this. Can anyone help?
$(".parent1 .child").addClass("new-class");
Or
$(".parent1>.child").addClass("new-class");
If you want to make sure only first child will be populated with class:
<div class="parent1">
<div class="child"> <!-- will have also "new-class" class -->
<div class="child"> <!-- will NOT have "new-class" class -->
</div>
</div>
</div>
.addClass('.new-class'); adds that class to something. You forgot to tell jQuery what something is, and caused a syntax error instead (which your browser console would have told you about if you had it open). I believe you want this:
$('.parent1 .child').addClass('.new-class');
Well, since you did tag this as just javascript...
HTML
<div class="parent1" id="parent">
<div class="child" id="child">
Content
</div>
</div>
CSS
.has-parent {
color: blue;
}
Javascript
var child = document.getElementById('child');
var parent = document.getElementById('parent');
if (child.parentNode == parent) {
child.className += ' has-parent';
}
DEMO
You could also do this with just CSS:
.child
{
color: red;
}
.parent .child
{
color: blue;
}
So long as the .parent .child rule comes after the single .child rule, it will override the color with blue. No extra work to change the color. If you need this extra class for some other reason the The User 518469 's answer is probably best.
I need to clone a styled DIV (id="#mirrorBG1") and amend the new div id to id="#mirrorBG2" then apply the class #mirrorBG2 in CSS to control the new div position & size etc.
Any ideas, please!
<div id="mirrorBG1">IMAGE#1 (*main image*) </div>
resulting in adding: <div id="mirrorBG2">IMAGE#1 (*same image*) </div>
#mirrorBG1 { width:50%; height:300px; background-color:#0F0"; float:left; clear:both; }
#mirrorBG2 { width:50%; height:300px; background-color:#FF0"; float:right; clear:both; }
Updated version:
var div2 = document.getElementById("mirrorBG1").cloneNode(true);
div2.setAttribute("id","mirrorBG2");
div2.className = "mirrorBG2";
After that you append your div wherever you want it to.
For example:
document.body.insertBefore(div2, null);
see jsfiddle
edit:
as stavarotti noted, classList isn't fully supported by IE versions previous to 10.
so instead of:
div2.classList.remove("mirrorBG1");
div2.classList.add("mirrorBG2");
You can do this instead:
div2.className = "mirrorBG2";
This will replace the class "mirrorBG1" with "mirrorBG2".
I updated the jsfiddle to show these changes.
If it isn't too much of a dependency for you, consider using jQuery and its clone() and append() methods. For more info see the jQuery API.
Im having problems with this code to work.. http://jsfiddle.net/whitewiz/z4fpx/
HTML
<h1 id="flip">Title<h1>
<div id="panel">
<p>Description that slides down</p>
</div>
<h1 id="flip">Title<h1>
<div id="panel">
<p>description that DOESN'T slide down</p>
</div>
JavaScript
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
and CSS
#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}
They work for first description, but doesn't work for the rest. I have about 18 #panels that should slide down, when I press on "Title" but only the first works.. Could you please find the missing piece in javascript that doenst allow multiple toggle?
Example on -> http://jsfiddle.net/whitewiz/z4fpx/
The first one works because that is the first element in the DOM with that id. Generally it is bad practice to have the same id assigned to multiple elements. Instead, use classes, like this:
HTML:
<h1 class="flip">Title<h1>
<div class="panel">
<p>Description that slides down</p>
</div>
<h1 class="flip">Title<h1>
<div class="panel">
<p>description that DOESN'T slide down (but does now)</p>
</div>
CSS:
.panel,.flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
.panel
{
padding:50px;
display:none;
}
I assume you only want to expand the panel following the header that you clicked on, in which case you need to get the closest element with the class name "panel" that follows the "flip" that was clicked on.
$(document).ready(function(){
$(".flip").click(function(){
$(this).next().find(".panel").slideToggle("slow");
});
});
Working example: http://jsfiddle.net/BBQJy/
The initial question seems to be lacking proper closing tags, an error that was duplicated in Nile's answer. Therefore, it didn't work for the original poster.
Based on Anna Brila's updated jsfiddle (http://jsfiddle.net/whitewiz/WuNHz/2), a possible correct solution would be:
$(".flip").click(function(){
$flip = $(this);
$content = $flip.next();
$content.slideToggle();
});
This is predicated on the use of classes instead of ids.
Full working example: http://jsfiddle.net/wy8gq1bj/1
Note: In the example, the only HTML I changed was the removal of the <br> immediately after the third , which was keeping the last item from expanding and collapsing.