Replace content of Div with content of another div jQuery - javascript

I would like to replace the content of a div with the contents of another div (which is hidden using css) by clicking on an image. However using a few methods suggested on here I can't seem to get it working.
my code is below:
html
<h3>Recent Callaborations</h3>
<div id="collaborations">
<img class="rec1" src="http://domain.com/michaelscott/wp-content/uploads/2013/02/url.png"/>
<div id="rec1">Some image caption that is hidden now and that will replace what is in the rec div below</div>
</div>
<div id="rec-box" class="rec">
this is the content that is to be replaced
</div>
js
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault()
jQuery('#rec-box').html($(this).next('#rec1')[0].outerHTML);
});
});
css
#collaborations {
width: 100%;
margin:0 0 10px 0;
padding:0;
}
#collaborations img {
display:inline-block;
}
.rec {
background: #EDEDED;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
padding: 10px;
}
#rec1, #rec2, #rec3, #rec4 {
display:none;
}

You simply need to set the html() of the correct div. Try this:
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault()
jQuery('#rec-box').html(jQuery(this).next().html());
});
});

jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault()
jQuery('#rec-box').html(jQuery("#rec1").html());
});
});

I would prefer the following solution :) Hope it helps
HTML
<h3>Recent Callaborations</h3>
<div id="collaborations">
<img class="rec1" src="http://cmagics.eu/michaelscott/wp-content/uploads/2013/02/url.png"/>
<div id="rec1">Some image caption that is hidden now and that will replace what is in the rec div below</div>
</div>
<div id="rec-box" class="rec">
this is the content that is to be replaced
</div>
JavaScript
$(document).ready(function() {
switchContent = function(ev) {
var el = $($(this).attr('href'));
if(el.length == 1) {
$('#rec-box').html(el.html());
}
ev.preventDefault();
};
$('.switchContent').on('click',switchContent);
});

Your original code seems to fail because you capture the entire hidden element, rather than just its contents, by using the outerHTML property (rather than innerHTML). This means the newly copied content still has <div id='rec1'...>, and is still hidden as a result of the css rule.
jQuery's html method can both get and set innerHTML, so that's the correct method here.
$(document).ready(function () {
$(".rec1").click(function (event) {
event.preventDefault();
$('#rec-box').html($('#rec1').html()); //replaces with contents of #rec1
});
});

You need to get $("#rec").contents() and .clone() it
You need to .append() it in $('#rect-box') after having .empty() it
jQuery(function($) {
$(".rec1").on('click',function(event) {
event.preventDefault();
$('#rec-box').empty().append(($('#rec1').contents().clone());
});
});

Related

How to add a class to a div on click, and remove the class by clicking elsewhere on the page

I would like to expand a div, filters, when filtertoggle is clicked. I would like to do this by adding the class on to filters. Then, when the user clicks anywhere else on the page, I would like to remove the on class, thereby closing filters.
Here is the code I have attempted:
jQuery(document).ready(function($) {
$('body').click(function(evt) {
if (evt.target.attr('class').includes('filtertoggle')) {
$(this).toggleClass('on');
$('.filters').slideToggle(200);
return;
} else {
$(this).element.className = element.className.replace(/\bon\b/g, "");
return;
});
As it stands, filters does not open.
Your logic has a couple of issues. Firstly, evt.target is an Element object, not a jQuery object, so it has not attr() method. You need to wrap it in a jQuery object to make that work. Then you can use hasClass() to check what class is on the target.
Also a jQuery object has no element property, so element.className will cause a syntax error. You can just use removeClass() in that case. Try this:
$('body').click(function(evt) {
if ($(evt.target).hasClass('filtertoggle')) {
$('.filtertoggle').addClass('on');
$('.filters').slideToggle(200);
} else {
$('.filtertoggle').removeClass('on');
$('.filters').slideUp(200);
}
});
body, html { height: 100%; }
.on { color: #C00; }
.filters { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filtertoggle">
FilterToggle
</div>
<div class="filters">
Filters...
</div>
You should also note that it may be possible to achieve this in CSS alone, depending on how your HTML is structured. You can use the :focus selector to do it, like this:
body, html { height: 100%; }
.filtertoggle { outline: 0; }
.filters {
opacity: 0;
transition: opacity 0.3s;
}
.filtertoggle:focus { color: #C00; }
.filtertoggle:focus + .filters { opacity: 1; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filtertoggle" tabindex="1">
FilterToggle
</div>
<div class="filters">
Filters...
</div>

Toggling HTML visibility using CSS and jQuery

Ok so I have a div that contains a canvas and a span which contains an image. I want it such that if the user hovers over or focuses on the div that the image inside of the span will appear. The image wil be invisible otherwise.
Long story short I want to have a canvas with a red 'X' on the corner that is only visible when the canvas is active
$('image-canvas').hover(function() {
$('delete-image').addClass('active');
}, function() {
$('delete-image').removeClass('active');
})
.delete-image {
position: absolute;
top: 0px;
right: 0px;
}
.delete-image>img {
width: 32px;
visibility: hidden;
}
.delete-image.active>img {
width: 32px;
visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canvas-container" tabindex="1">
<canvas id="imageCanvas"></canvas>
<span class="delete-image">
<img src="file:///E:/Apps/Emoji-App/emojis/icons/if_erase_delete_remove_wipe_out_181387.png"/>
</span>
</div>
The hover event fires just fine but the image refuses to toggle visibility. Any help?
When you use a class within your selector, write it like this:
$('.myDiv')
When you use an ID within your selector, write it like this:
$('#myDiv')
For further informations, check out jQuery's learning center website.
Seems like you have misspelled or have not specified the jQuery selector type (class . or id #). Please try this:
$('#imageCanvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
See here .
$("#control").mouseover(function(){
$('#img').show();
});
$("#control").mouseout(function(){
$('#img').hide();
});
#img{
display:none;
}
#control{
margin-bottom:10px;
padding:5px;
background-color:#eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='control'>Show/Hide</div>
<img src='https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg' id='img'>
The question is not well-phrased, so I ain't sure I totally understood what you wanted.
When you try to select by class, don't forget the dot '.'
$('image-canvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
When using functions 'addClass', 'removeClass', 'toggleClass', etc. - you don't use the '.' sign because it is a function that refers only to classes. On the other hand, when using jQuery selector $(' ') or vanilla querySelector(' '), you should declare what kind of attribute you are selecting by, those will be '#' for ID, '.' for Class, and if you want to select by anything else you can use $('*[anyattribute=anyvalue]'), in your clase it could be $('span[class=delete-image]').
Good luck

Targeting previous div in javascript or css

HTML code:
<div class="content">
<textarea> hello.png </textarea>
</div>
<div class="content-btn">
Click me
</div>
Javascript code:
$(".button").click(function() {
if ($(this).parent().previousSibling('.content').css('display') == 'none'){
$('.content').hide();
$(this).parent().previousSibling('.content').show();
}else {
$('.content').hide();
}
});
How would I go about only showing the textarea when 'Cick me' is clicked or hovered preferably in css but if not javascript. Thanks guys
https://jsfiddle.net/uway5hhg/8/
As exercise you could do this effect in pure css (using :target pseudoclass and a long delay in a simple transition) if you add a close button just below the textarea
http://codepen.io/anon/pen/JYoMRK
<div class="content" id="text">
<textarea> hello.png </textarea><br />
Close
</div>
<div class="content-btn">
Open
</div>
CSS
#text {
overflow: hidden;
height: 0;
opacity: 0;
transition: opacity 0s 999999s;
}
#text:target {
opacity: 1;
height: auto;
transition-delay: 0s;
}
#text:target ~ div a.button { display: none; }
Anyway if you look for a straight jQuery approach, a simple toggle() is enough (you might have to hide the .content element via css depending on the initial condition of your textarea)
https://jsfiddle.net/uway5hhg/39/
$(".button").click(function() {
var content = $(this).parent().prev('.content');
content.toggle();
});
As far as I know there is no way to catch previous sibling in CSS.
But it works with jQuery, here is your slightly changed code:
$(".button").on('click', function() {
var ele = $(this),
par = ele.parent(),
sbl = par.prev();
if (sbl.css('display') == 'none'){
$('.content').hide();
sbl.show();
}else {
$('.content').hide();
}
});
Working example is here: https://jsfiddle.net/y0ab3n0L/
That should do it's job
JS:
$(".button").click(function() {
var contentBtn = $(this).parent(".content-btn");
var content = $(contentBtn).prev(".content");
var textarea = $(content).find("textarea");
$(textarea).toggle();
});
or event shorter:
$(".button").click(function() {
$(this).parent(".content-btn").prev(".content").find("textarea").toggle();
});
https://jsfiddle.net/uway5hhg/21/
Hope this helps :)
Solution provided by Fabrizio is a good one if you want no javascript.
However you can also modify the DOM to have a similar effect.
<div class="content-wrapper">
<div class="content" id="text">
<textarea>hello.png</textarea>
</div>
Click me
</div>
CSS
.content {
display:none;
}
.content-wrapper:hover .content {
display:block;
}
.content-wrapper:hover .button {
display:none;
}
https://jsfiddle.net/2Lsszgqz/
There is no such CSS pseudo element - a.button:click, so only JS solution will work (without changing your HTML structure). You can also get to close of it using :focus CSS pseudo class. But you will lack to go up one level in CSS and then show the textarea. So, only solution left is using JS.
In your sample JS code you have used .previousSibling('.content') which is native JS, which you are calling on jQuery object, that's why it will not work. jQuery equivalent of this function is .prev('.content')
Correct Syntax would be -
$(".button").click(function() {
if ($(this).parent().prev('.content').css('display') == 'none'){
$('.content').hide();
$(this).parent().prev('.content').show();
}else {
$('.content').hide();
}
});
Working Fiddle

Prevent children divs from moving while div toggle

I'm new and have I think very simple problem to solve.
I have 4 buttons to show/hide each panel. What should I do to prevent child divs from moving to te left while hiding some div?
I prefer them to stay at the initial position.
This is my code:
HTML:
<button class="panel-button" data-panel="panel1">1</button>
<button class="panel-button" data-panel="panel2">2</button>
<button class="panel-button" data-panel="panel3">3</button>
<button class="panel-button" data-panel="panel4">4</button>
<div class="wrapper">
<div id="panel1">1</div>
<div id="panel2">2</div>
<div id="panel3">3</div>
<div id="panel4">4</div>
</div>
JS:
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
$('#'+panelId).toggle();
});
});
CSS:
.wrapper {
overflow: hidden;
width: 420px;
}
.wrapper > div {
width: 100px;
height: 100px;
background: green;
float: left;
margin-left: 5px;
margin-top: 10px
}
Apply css rule opacity = 0; to the div, instead of hiding it.
Like this:
$('.panel-button').on('click',function(){
var pnl = $('#' + $(this).data('panel'));
pnl.css('opacity', pnl.css('opacity') == '0' ? '1' : '0');
});
Solution for clickability issue:
$('.panel-button').on('click',function(){
var pnl = $('#' + $(this).data('panel'));
if(pnl.is(':visible'))
$('<div></div>').appendTo(pnl).width(pnl.width());
else
pnl.next().remove();
pnl.toggle();
});
But still you can use another approach
You can use the visibility property in CSS to achieve this as shown in the below Fiddle link : link
JS Snippet:
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
console.log($('#'+panelId).css('visibility'));
if($('#'+panelId).css('visibility') === 'hidden') {
$('#'+panelId).css('visibility','visible');
}
else {
$('#'+panelId).css('visibility','hidden');
}
});
});
The CSS visibility is designed to keep the space a DOM object occupies, but not actually rendering it. Opacity changes its appearance, but not its behavior (eg. still clickable).
So instead of .toggle(), combine visibility with jQuery's .toggleClass():
jsFiddle solution
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
$('#'+panelId).toggleClass('hideMe');
});
});

.replaceWith() to replace content in a div for different link elements

I am trying to load a div with different content based on the link I click...
While it seems to work for the first link when I click it, clicking the other links only replaces the content with the same content for 'encodeMe' , yet I have specified different content that I want to replace for 'htmlize-me'
The first run-through of this I did not use jQuery's .bind() function. I simply used .click() , and both had the same result. Looking through the jQuery API I thought using the .bind() function would bind each function within it to that particular page element, but it seems to apply it to all my links.
I've achieved the same effect using .hide and .show to toggle divs but I want to be more elegant about how I do that, and this was my attempted alternative...
here's the relevant html:
<label for="list-root">App Hardening</label>
<input type="checkbox" id="list-root" />
<ol>
<li id="encode-me"><a class="show-popup" href="#">encodeMe()</a></li>
<li id="htmlize-me"><a class="show-popup" href="#">htmlizeMe()</a></li>
</ol>
<div class="overlay-bg">
<div class="overlay-content">
<div class="the-content"></div>
<br><button class="close-button">Close</button>
</div>
</div>
here's the script I made to trigger the content change:
$('#encode-me').bind('click' , function() {
$('div.the-content').replaceWith('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>' +
'Found in <p>[web root]/redacted/redacted.asp</p>');
});
});
$('#htmlize-me').bind('click' , function() {
$('div.the-content').replaceWith('Hi, Im something different');
});
});
Try something like this:
Use html() instead of replaceWith()
$('#encode-me').bind('click' , function() {
$('div.the-content').html('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>' +
'Found in <p>[web root]/redacted/redacted.asp</p>');
});
});
$('#htmlize-me').bind('click' , function() {
$('div.the-content').html("Hi, I'm something different");
});
});
replaceWith does exactly what it sounds like, it replaces the div with the h3, so when you click the second link there is no div.
Try setting the innerHTML instead
$('#encode-me').on('click' , function() {
$('div.the-content').html('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>Found in <p>[web root]/redacted/redacted.asp</p>');
});
$('#htmlize-me').on('click' , function() {
$('div.the-content').html('Hi, I\'m something different');
});
So I figured out a more clever way to do this! Use the DOM to your advantage - set up a nested list structure and change the content using .find() on parent and child elements the list.
Markup
<span style="font-size:1.4em">Type
<ul class="row">
<li>Blah
<div class="overlay-content">
<p></p>
<p class="changeText">Blah</p>
</div>
</li>
<li>Blah2
<div class="overlay-content">
<p></p>
<p class="changeText">Blah2</p>
</div>
</li>
</ul>
</span><br>
<!-- OVERLAYS -->
<div class="overlay"></div>
CSS
.close {
border-radius: 10px;
background-image: url(../img/close-overlay.png);
position: absolute;
right:-10px;
top:-15px;
z-index:1002;
height: 35px;
width: 35px;
}
.overlay {
position:absolute;
top:0;
left:0;
z-index:10;
height:100%;
width:100%;
background:#000;
filter:alpha(opacity=60);
-moz-opacity:.60;
opacity:.60;
display:none;
}
.overlay-content {
position:fixed!important;
width: 60%;
height: 80%;
top: 50%;
left: 50%;
background-color: #f5f5f5;
display:none;
z-index:1002;
padding: 10px;
margin: 0 0 0 -20%;
cursor: default;
border-radius: 4px;
box-shadow: 0 0 5px rgba(0,0,0,0.9);
}
Script
$(document).ready(function(){
$('.show-popup').click(function() {
var ce = this;
$('.overlay').show('slow', function() {
$(ce).parent().find('.overlay-content').fadeIn('slow');
});
});
// show popup when you click on the link
$('.show-popup').click(function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var docHeight = $(document).height(); //grab the height of the page
var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
$('.overlay').show().css({'height' : docHeight}); //display your popup and set height to the page height
$('.overlay-content').css({'top': scrollTop+100+'px'}); //set the content 100px from the window top
});
/*
// hides the popup if user clicks anywhere outside the container
$('.overlay').click(function(){
$('.overlay').hide();
})
*/
// prevents the overlay from closing if user clicks inside the popup overlay
$('.overlay-content').click(function(){
return false;
});
$('.close').click(function() {
$('.overlay-content').hide('slow', function() {
$('.overlay').fadeOut();
});
});
});

Categories