Move element with jQuery - javascript

I have a sidebar with expandable links. When they expand past a certain point I want to move some text from one div to another (red to blue). When I expand and collapse the links, at some point, the text I was planning to move just disappears.
There are two problems:
The text should move to the blue div when I expand, back to red when I collapse
The text disappears altogether, not moving to the other div.
Here is my html:
<div id="sidebar">
<div>
Test 1
<p class="cal-desc">Lorem ipsum</p>
</div>
<div>
Test 2
<p class="cal-desc">Lorem ipsum</p>
</div>
<div>
Test 3
<p class="cal-desc">Lorem ipsum</p>
</div>
</div>
<div class="red">
<p>Just some random text</p>
</div>
<div class="blue">
</div>
Here is the jQuery/js code:
$(document).ready(function() {
var isExtended = false;
function placeTiles() {
// When to move content from .red to .blue
if ($('#sidebar').height() > 150 && isExtended == false) {
$('.red').appendTo($('.blue'));
isExtended = true;
// When to move content from .red to .blue
} else if ($('#sidebar').height() <= 150 && isExtended == true) {
$('.blue').appendTo($('.red'));
isExtended = false;
}
}
$('.cal-desc').hide();
// Check how thing are on init
placeTiles();
$('.cal-title').click(function() {
$(this).siblings('.cal-desc').toggle();
placeTiles();
});
});
Here is a link to my jsfiddle.
I'm really a newbie at javascript so any suggestion for my code is most welcome!

See this updated fiddle: http://jsfiddle.net/awden/3/
The problem is that you are appending the entire .red element to the inside of the .blue element
$('.red').appendTo($('.blue'))
Instead, you want to append the contents of .red to .blue, and vice versa. In other words, you want something like:
$('.red > p').appendTo($('.blue'))

I think want you mean to do is move the <p> from .red to .blue and back again. To do that, just add > p to each selector, like this:
$('.red > p').appendTo($('.blue'));
and
$('.blue > p').appendTo($('.red'));

Related

Make div clickable, only when anchor is present in div (multiple divs)

Given a basic structure how can I turn a series of divs into links without turning every div into a link? Here's an example:
<div class="boxes">
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
</div>
And the associated jQuery I'm using to make the divs clickable:
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
The problem I'm running into is the click function gets applied to all divs instead of only those with links.
The desired behavior is to only create a fully clickable div only when an anchor element is found.
For the purposes of this use case, the div (.box) is generated dynamically and wrapping the element in an anchor tag (<div> </div>) is not possible.
Fiddle: https://jsfiddle.net/fu8xLg0d/
Because you add event listeners on all the .boxes .box classes, which are all your divs.
Just add something like :
$(".boxes .box").has('a')...
to narrow it to those only containing an a element
JSFiddle
use .parent to solve your purpose:
$(document).ready(function() {
if($('.boxes p a').length){
$("a").parent().parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
But yes, it can even create a problem so i will say to give a class to your link and then call its parent... :)
Plotisateur just beat me by a minute or two! :P
if($('.boxes p a').length){
$(".boxes .box").has('a').click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
Here's the code anyway: https://jsfiddle.net/fu8xLg0d/1/
You can try this.
$(document).ready(function() {
var anchorbox =$(".boxes p a");
if(anchorbox.length>0){
$(anchorbox).parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
div (.box) is generated dynamically.
Delegate the click event from the body to the target div and on click on the element check if it has anchor tag. For adding the pointer icon create a separate function which will add the icon to the div only if it has an anchor tag as child
$(document).ready(function() {
// separate function to add pointer only if a is present
addClassToElem();
$("body").on('click', '.box', function() {
if ($(this).find('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
})
});
function addClassToElem() {
$('.box a').each(function(a, b) {
$(this).parent().addClass('linkIcon')
})
}
.linkIcon {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
</div>
This little change, helps you to resolve the issue.
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
});
}
});
the difference from your code is, additionally add a checking
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}

Changing image when div is active on SlideToggle

I currently have a setup with three seperate buttons that open three divs. I want one div (namely lockedin) to be open at the start. Furthermore, the divs should close when another is opened by the buttons, which I have accomplished now.
There is one more thing I require and cannot seem to get working properly. Is there a way to show which div is currently active? So when the page is loaded, button2 shows an orange filled button (which I have as an image) and the other two buttons show the white filled button. When another div is selected by means of for example button 1, the button 2 should change to the white filled button, and the button 1 should change to the orange filled button. I have the image SRC's, but just don't know how to select the image based on the active state of its given div.
Thank you in advance.
jQuery(document).ready(function( $ ){
//Start of Jquery
$('.button1').click(function(){
if ($('.product').css('display') === 'none') {
$('.product').slideToggle('slow');
}
$('.developers').slideUp();
$('.lockedin').slideUp();
});
$('.button2').click(function(){
if ($('.lockedin').css('display') === 'none') {
$('.lockedin').slideToggle('slow');
}
$('.product').slideUp();
$('.developers').slideUp();
});
$('.button3').click(function(){
if ($('.developers').css('display') === 'none') {
$('.developers').slideToggle('slow');
}
$('.product').slideUp();
$('.lockedin').slideUp();
});
// End of Jquery
});
.product {
display:none;
color: yellow;
}
.lockedin {
color:yellow;
}
.product_active{
display:none;
}
.developers {
display:none;
color: yellow;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<img src="http://www.mindaffect.nl/wp-content/uploads/2017/12/product-holder.png" class="button1" alt="Expand"/>
<img src="http://www.mindaffect.nl/wp-content/uploads/2017/12/product_active.png" class="product_active" alt="product_active" />
<img src="http://www.mindaffect.nl/wp-content/uploads/2017/12/lockedin-holder.png" class="button2" alt="Expand"/>
<img src="http://www.mindaffect.nl/wp-content/uploads/2017/12/developers-holder.png" class="button3" alt="Expand"/>
<div class="product">
Testdiv1
</div>
<div class= "lockedin">
Testdiv2
</div>
<div class = "developers">
Testdiv3
</div>

Testing if a click is in a div and all its children

I am facing an issue about this.
<div id="1">
<div id="2">
</div>
<div id="3">
<div id="4">
</div>
</div>
</div>
<div id="others_div">
</div>
I want to add the class "hidden" to "1" when I click on something which is not "1" nor one of its children.
Now I am using this but I have a lack of imagination for solving this issue...
document.onclick = function(e)
{
if(e.target.id!="1")
{
$("#1").addClass("hidden");
}
}
Well, to avoid e.stopPropagation() (maybe you want that event to bubble up to some other ancestor) You can check if it is not clicked on #1 nor on it's children like this:
$('body').on('click', function(e) {
if (!((e.target.id== "1") || $(e.target).closest('#1').length)) {
$("#1").addClass("hidden");
}
});
You could use a jQuery check like the following one to check if the current element is your 1 element or traverse the DOM to see if the current target is contained within an element with an ID of 1 :
<script>
$(function(){
// Trigger this when something is clicked
$(document).click(function(e){
// Toggle the hidden class based on if the current element is 1
// or if it is contained in an element with ID of 1
$("#1").toggleClass('hidden',!((e.target.id== "1") || $(e.target).closest('#1').length))
});
});
</script>
Generally, you should avoid using ID attributes that only consists of numbers as they are not valid (ID attributes must begin with a letter). Ignoring this could result in some issues with regards to CSS or jQuery selection.
JQuery
$('body').on( "click", function(e) {
if(e.target.id !== "1")
{
$("#1").addClass("hidden");
}
});
I think you want this
// taken from http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element
$('html').click(function() {
//Hide the menus if visible
alert('hide');
});
$('#one').click(function(event){
event.stopPropagation();
});
div#one {
background: yellow;
}
div#others_div {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="one">
div one
<div id="2">
div two
</div>
<div id="3">
div three
<div id="4">
div four
</div>
</div>
</div>
<div id="others_div">
other div
</div>

How to simultaneously hide and show content and vice versa?

I have a problem and I need your help. I have several links (in <aside>) leading to several different menus (in <section>). On click over the link, only the relevant div in <section> is shown, the rest are hidden. This part is ok and working. What is not working is when I click over an image:
the current div (.menu) in <section> should be hidden;
the same picture (with bigger size) should be shown;
when you click once again over the big image, the big image should disappear and the current div in .menu (the one that was hidden on the first step) should appear one more time. Sort of toggling between content.
So if I click on a picture on the "second div" content, the same picture with bigger size should be show (the "second div" content should be hidden) and when I click once again over the big picture it should disappear and the "second div" content to be returned.
I tried with toggle() but had no success. Either I did not use it correctly, or it is not suitable for my case. This is where I managed to reach to.
I will really appreaciate your support - how to show only the hidden div, not all hidden div's. Right now, when you click on the big image it did not show the hidden div.
$(window).on("load", function() {
$("div.menu:first-child").show();
});
$(".nav a").on("click", function() {
$("div.menu").fadeOut(30);
var targetDiv = $(this).attr("data-rel");
setTimeout(function() {
$("#" + targetDiv).fadeIn(30);
}, 30);
});
var pictures = $(".img-1, .img-2").on("click", function() {
$("div.menu:active").addClass("hidden");
//how to reach out only the current, active div (not all div's in .menu)?
$(".menu").hide();
var par = $("section")
.prepend("<div></div>")
.append("<img id='pic' src='" + this.src + "'>");
var removePictures = $("#pic").on("click", function() {
$(this).hide();
$(".hidden").show();
});
});
.menu {
width: 100%;
display: none;
}
.menu:first-child {
display: block;
}
.row {
display: inline-block;
width: 100%;
}
.img-1,
.img-2 {
width: 120px;
height: auto;
}
<!doctype html>
<html>
<head>
</head>
<body>
<aside>
<ul class="nav">
<li>To first div
</li>
<li>To second div
</li>
<li>To third div
</li>
</ul>
</aside>
<section>
<div class="menu" id="content1">
<h3>First Div</h3>
<div class="present">
<div class="row">
<div>
<p>Blah-blah-blah. This is the first div.</p>
<img class="img-1" src="http://www.newyorker.com/wp-content/uploads/2014/08/Stokes-Hello-Kitty2-1200.jpg">
</div>
</div>
<div class="row">
<div>
<img class="img-2" src="https://jspwiki-wiki.apache.org/attach/Slimbox/doggy.bmp">
<p>Blah-blah-blah. This is the first div.</p>
</div>
</div>
</div>
</div>
<div class="menu" id="content2">
<h3>Second Div</h3>
<div class="present">
<div class="row">
<div>
<p>
Blah-blah-blah. This is the second div.
</p>
<img class="img-1" src="http://www.newyorker.com/wp-content/uploads/2014/08/Stokes-Hello-Kitty2-1200.jpg">
</div>
</div>
<div class="row">
<div>
<img class="img-2" src="https://jspwiki-wiki.apache.org/attach/Slimbox/doggy.bmp">
<p>
Blah-blah-blah. Yjis is the second div.
</p>
</div>
</div>
</div>
</div>
<div class="menu" id="content3">
<h3>Third Div</h3>
<div class="present">
<div class="row">
<div>
<p>
Blah-blah-blah. This is the third div.
</p>
<img class="img-1" src="http://www.newyorker.com/wp-content/uploads/2014/08/Stokes-Hello-Kitty2-1200.jpg">
</div>
</div>
<div class="row">
<div>
<img class="img-2" src="https://jspwiki-wiki.apache.org/attach/Slimbox/doggy.bmp">
<p>
Blah-blah-blah. This is the third div.
</p>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</body>
</html>
Sorry for the ugly sketch and pictures - it is only to get an idea what it should look like....
In general, it's poor form to ask on Stack Overflow how to code for a specific behavior. However, that takes some understanding of the libraries you're using, and what you are trying to achieve. Hopefully, my answer will help you better articulate and form your questions in the future.
Here's a fiddle for you: https://jsfiddle.net/hwd4b0ag/
In particular, I've modified your last click listener:
var pictures = $(".img-1, .img-2").on("click", function() {
var parentDiv = $(this).closest('div.menu').hide();
var blownUpPic = $("<img>").attr({
id: 'pic',
src: this.src,
'data-parent': parentDiv.attr('id')
})
.appendTo("section")
.on('click', function() {
$('#' + $(this).attr('data-parent')).show();
$(this).remove();
});
});
Now, let's review it!
First,
var parentDiv = $(this).closest('div.menu').hide();
In a jQuery listener, the this variable stores the current javascript DOM element that is the recipient of the event listener. In your case, it refers to an element that matches ".img-1, .img-2".
.closest(selector) will traverse up the DOM (including the current element) and find the first matching element for the provided selector. In this case, it finds your container div with class menu. Then we hide that div and save a reference to it in a variable.
Next, we create a full-sized version of the picture and assign it some attributes:
var blownUpPic = $("<img>").attr({
id: 'pic',
src: this.src,
'data-parent': parentDiv.attr('id')
})
We set the data-parent attribute to the id of our container div, so we have a reference back to it later.
We then add our image to the DOM:
.appendTo("section")
And declare a new click listener for it:
.on('click', function() {
$('#' + $(this).attr('data-parent')).show();
$(this).remove();
});
With $(this).attr('data-parent') we use the reference to our container div that we assigned earlier, and then retrieve that element by its id. We unhide the container div and remove the full-sized image.
All done!
There are better ways to code this, but I think this is a good next step for you that's analogous to your current code.

How to use JavaScript to change div backgroundColor

The HTML below:
<div id="category">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</div>
When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS: hover)
I know this can use CSS (: hover) to do this in modern browser but IE6 doesn't work.
How to use JavaScript (not jQuery or other JS framework) to do this?
Edit:how to change the h2 backgroundColor too
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
this.style.backgroundColor = 'green';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
this.style.backgroundColor = 'transparent';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'transparent';
};
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
It's very simple just use a function on javaScript and call it onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
Change Bacckground Color
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.
Example:
div.classname:hover
{
background-color: black;
}
This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
Happy programming!
If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.
<style type="text/css">
.content {
background: #ccc;
}
.fakeLink { /* This is to make the link not look like one */
cursor: default;
text-decoration: none;
color: #000;
}
a.fakeLink:hover .content {
background: #000;
color: #fff;
}
</style>
<div id="catestory">
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
</div>
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>

Categories