JavaScript: not able to alert output value - javascript

The code is pretty simple.
HTML:
<div class="simpleDiv" id="Child1" onmouseover="expandDiv(this);"></div>
CSS:
.simpleDiv {
background-color: red;
width: 100px;
height: 50px;
margin: 5px;
margin-left: 50px;
opacity: 1;
}
JavaScript:
function expandDiv(object){
alert(document.getElementById(object.id).style.height);
}
Why am I not able to alert the height of the div like this? If I alert the id or class using the function hasAttribute, thats working fine but not able to alert the css properties of the elements.
Any help appreciated!

Why not just alert(object.style.height)?
Anyway, the reason it doesn't work is because elem.style.property only works with inline style="..." attributes. To take into account all styles, you need this:
alert(window.getComputedStyle(object).height)
Older versions of IE don't support this, but it's a very easy shim:
window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;};

function expandDiv(object){
alert(document.getElementById(object.id).innerHeight);
}

try using:
alert(document.getElementById(object.id).offsetHeight);
Here is description:
offsetHeight on MDN

Use JQuery:
alert($('#Child1').css("height");
Or to change the attribute, use:
$('#Child1').css("height", value )
Ignore if you don't want JQuery.

Related

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

Merging values from 2 CSS classes into 1 and sum up the margins and paddings

This is in my client's project requirements. I am just giving example with margin only. if there are two CSS classes and have properties like.
CSS
.selector-1 {
margin-top: 20px;
}
.selector-2 {
margin-top: 30px;
}
HTML
<div class="selector-1 selector-2">content</div>
We all know it will overwrite the properties from one class to another, but in this case, a client wants to add both margin-top and apply. So he is expecting margin-top:50px.
I know there is no way to do it in CSS.
Can anyone suggest something? I want to avoid using JS/jQuery. However, at the end, I can use, if it is possible to do it.
you can not do it with pure css anyway, because for do it you must get margin-top of classes and sum them.the problem is right here you can't access to another class through pure css.
but you can do it with javascript.
Why don't you:
.selector-1.selector-2 { margin-top: 50px }
Will give you 50px margin-top as both .selector-1 and .selector-2 margin-top's are combined to one margin-top called .selector-1.selector-2.
You can't do it with pure CSS, so here is the solution with jQuery https://jsfiddle.net/z5pdt17j/1/
$('body').append('<div class="selector-1 hidden" id="div1"></div><div class="selector-2 hidden" id="div2"></div>');
var tmargin = parseInt($('#div1').css('margin-top')) + parseInt($('#div2').css('margin-top'));
$('div#divTest').css({
'margin-top': `${tmargin}px`
});
$('#div1 , #div2').remove();
.selector-1 {
margin-top: 20px;
}
.selector-2 {
margin-top: 30px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selector-1 selector-2" id="divTest">content</div>
Hope this will help you.
try this with jquery : easy solution
<div data-margin1="20" data-margin2="30" class="content">content</div>
(function(){
let content = $('.content');
let margin1 = content.data('margin1');
let margin2 = content.data('margin2');
content.css({'margin-top':margin1+margin2});
}())

Show div if another div has content

So I don't get why this isn't working. I want to show a Div when another div has a value. I got this code from stackoverflow and it's pretty simple. But it doesn't work for me. No console errors..
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
});
If the html value of .txt is larger then 0 then show btn-01.
But it doesn't. In my web inspector it just says:
<div style="display: block;" class="btn-01"><p>Things</p></div>
If I remove the script it says:
<div class="btn-01"><p>Things</p></div>
So it does do something. I tried changing the show to hide. But no go.
<div style="display: none;" class="btn-01"><p>Things</p></div>
I tried:
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').addClass('showme);
}
});
btn-01 css:
.btn-01 {
background: #f60;
color: #fff;
border-radius: 2px;
padding: 5px;
text-align: center;
margin: 40px auto 0px auto;
width: 90%;
}
But that didn't work either. Does anyone know whats going on here?
Maybe I should work with an else statement? Help would be much appreciated.
JsFiddle
You need to either set the button to display none prior to the window loading or add an "else" statement to hide the element:
.btn-01{
display:none;
}
OR
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
else
{
$('.btn-01').hide();
}
});
See the fiddle: https://jsfiddle.net/r89gg7tp/
IMPORTANT TO CONSIDER
If you have entered a line break between the starting and closing tags of the element, this will add to the length. You need to set the txt div to be in the following format:
<div class='txt'></div>
It may be better to change your function to this:
$(document).ready(function(){
if ($(".txt").html().trim(' ').length > 0) {
$('.btn-01').show();
} else {
$('.btn-01').hide();
}
});
This way you trim the whitespace before checking.
See the second fiddle: https://jsfiddle.net/r89gg7tp/3/
You need to hide the btn-01 with a "display:none" in the stylesheet and then execute your script.
I think you are having a "display:none !important" which is overriding the jquery show() function inline style.
This might help you.
$(document).ready(function(){
if (!$.trim($(".txt").html())){
$('.btn-01').addClass('showme');
}
});
Please let me know if you've any queries.
You can use .contents() with .toggle():
$(document).ready(function() {
$('.btn-01').toggle($(".txt").contents().length > 0);
});
.btn-01{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="txt">
<h3>Things Title</h3>
</div>
<div class="btn-01">
<p>Things</p>
</div>
You guys where all right. I needed to place the code in some Session file (Ajax). Now its working with the original code and even some that you provide.
Thanks!

click to change background toggle

When I click on it changes background. It works fine. But what if I want to click on it again to restore the original background? I have this code:
jQuery(document).ready(function($) {
$(".select").on("click", function () {
$(this).css("background-image", "url(images/selected.png)");
});
});
Here is jsfiddle EXAMPLE
Basically when I click on the div it changes the background, which is fine. But I want to have ability to click on it again to restore the original background.
It will be an alternative solution for tick box, but just for demo purposes.
Thanks
JS
replace
$(this).css("background-image", "url(images/selected.png)");
with
$(this).toggleClass("active");
Style
#multiselect .active {
background-image: url('...');
}
Fiddle http://jsfiddle.net/09xgrhxo/4/
Instead of using .css() to change the background-image I would add a class in your CSS and use .toggleClass().
Also be aware that simply adding a class will not be specific enough because your css is using:
#multiselect .select
you're going to have to target the class you add as a child of #multiselect:
#multiselect .change
CSS
#multiselect .change{
background-image: url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)
}
JS
$(".select").on("click", function () {
$(this).toggleClass("change");
});
FIDDLE
You could use data-* attribute.
$('.select').attr('data-img', $('.select').css('background-image'));
$(".select").on("click", function() {
$(this).css("background-image", ($(this).css('background-image') == $(this).data('img')) ? "url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)" : $(this).data('img'));
});
#multiselect .select {
background: url(http://t0.gstatic.com/images?q=tbn:ANd9GcQF_ErOlc78eOGZaEWb-dwPkrv2uyAoKx0Pbn3-e0tAZoUDSQRCsA) center;
width: 250px;
height: 100px;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="multiselect">
<div class="select">Option1</div>
<div class="select">Option2</div>
<div class="select">Option3</div>
</div>
Instead of writing background-img url in javascrpt, I would suggest to create two classes having same properties but different background-img url which you want to toggle. so here we will be toggling class (ultimately background-img) in javascript.
see jsfiddle [example][1]
[1]: http://jsfiddle.net/09xgrhxo/13/

Changing DIV Background Image with JavaScript Not Working

I'm trying to change a div background image on hover, I want to do this with JaveScript so that it works cross browser without any issues. The current code I have is:
<div class="staff" style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);" onmouseover="this.style.background=url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);" onmouseout="this.style.background=url(wp-content/uploads/2013/08/IMG_1828-300x237.png);">
</div>
CSS:
.staff{
width: 300px;
height: 237px;
}
Can anybody see what is causing the problem?
<style>
.staff{
width: 300px;
height: 237px;
background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);
}
.staff:hover {
background-image: url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);
}
</style>
<div class="staff"></div>
You can use simple css too.. and it will work on all browsers
.staff { background: url("url/img.png")}
.staff:hover { background: url("url/hoverimg.png")}
<div class="staff"></div>
Better use CSS than inline CSS and javascript to achieve the effect.
If you still want to do it inline, here is a example.
jsfiddle
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
you can use css like this:
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
or javascript like:
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
WORKING DEMO
CHANGE I MADE
onmouseover="this.style.background='url()';"
You have to enclose the url in single qoutes...
I would also suggest you use CSS rather than JS to do this. But since you asked how to do it in JS, this is your answer
Most browser should support :hover in css, so there is no need to use JavaScript for this (relevant fiddle here):
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
If you really want to use JavaScript, than you have to wrap url(...) in quotes like so:
<div class="staff"
style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);"
onmouseover="this.style.background='url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png)';"
onmouseout="this.style.background='url(wp-content/uploads/2013/08/IMG_1828-300x237.png);'">
</div>
I think you can use this script :
$('.staff').mouseover(function() {
$(this).attr('style',"background:grey;");
})
$('.staff').mouseout(function() {
$(this).attr('style',"background:white;");
})
Change the color to the image path.
$(document).ready(function(){
var staff = $(".staff"); //Avoid repeated traverse
$("img").hover(function(){
staff.css("background",'url(' + $(this).attr('src') + ')');
//Assuming you want to set current image as background image
});
$( "img" ).mouseout(function(){
staff.css("background","none");
});
});
Okay this works for me so when you hover over an image the background of the set div is changed. So when ever you hover over an image .staff background is changed.
I believe that is what you want?

Categories