OnLoad on an element - javascript

Suppose, as exercise, we have to dynamically adjust a div height to the one of the previous div.
My question is how to apply that on the "onload" of the element, in order to have each div's individul previous element...
Suppose the code
$(".description").css("height",
$(".description").prev(".pic").height());
.pic {float: left; width: 50%; border: 1px solid red;}
.description {border: 1px dotted green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<figure>
<div class="pic">pic1<br>this is a big pic</div>
<div class="description">one is OK</div>
</figure>
<figure>
<div class="pic">pic2<br>this<br> is a pic2<br>this is another big pic</div>
<div class="description">two is NOK</div>
</figure>
<figure>
etc...
</figure>
</div>
you can see, the code works only for the first description, the second description is still adjusted to the first one.
PS.
Please do not propose to reformat the HTML, I am wondering how to apply some JS code for a specific HTML element: something like to have "onload" on a div element, to correctly identify the previous element.

You can take advantage of the fact that .css() can be passed a function:
$(".description").css("height", function() {
var element = this; // current "description" element
return $(element).prev(".pic").height() + "px";
});
The value of this inside the callback function will be, in turn, each element that matches the selector (".description").

This code will do, you need to iterate through all the .pics
$(document).ready(function() {
$(".description").each(function(){
var height = $(this).parent().find('.pic').height();
$(this).css('height',height);
})
});

Related

Reset Border style

I have a image that is currently being styled with Jquery once it's clicked. I eventually hide it in Javascript. I want to reshow it, but I want it to have the border removed.
Here is HTML:
<div id="playOptionsWager" style="display: none">
<h4>Choose your move to beat the computer!</h4>
<img id="clickedRockWager" src="img/rock.jpg" onclick="playWagerRock()" />
<img id="clickedPaperWager" src="img/paper.jpg" onclick="playWagerPaper()"/>
<img id="clickedScissorsWager" src="img/scissors.jpg" onclick="playWagerScissors()" />
</div>
Jquery:
$(function () {
$("img").on("click",function() {
$(this).siblings().css('border','0px')
$(this).css('border', "solid 2px red");
});
});
Here is what I was trying in Javascript:
function autobet() {
coinBalance -= currentBet*2;
alert(getBalance());
document.getElementsByTagName("IMG").style.border="";
}
However when it reshows the div it has the border on it still.
Thanks for the help!
Your issue is that document.getElementsByTagName("IMG") returns a collection of elements, so simply applying .style.border on this collection won't work. Instead, you need to loop over this collection, and set every image within it to have no border using .style.border = 0;:
See working example (with div) below:
function removeBorder() {
[...document.getElementsByTagName("div")].forEach(elem => {
elem.style.border = 0;
});
}
.box {
height: 100px;
width: 100px;
background: black;
display: inline-block;
}
.active {
border: 3px solid red;
}
<div class="box"></div>
<div class="box active"></div>
<div class="box"></div>
<br />
<button onclick="removeBorder()">Remove border</button>
Also note that [...document.getElementsByTagName("IMG")] is a way of converting the collection of elements into an array of elements, which thus allows us to use the .forEach method to loop over it.
You started with jQuery, let's continue with jQuery.
function autobet() {
coinBalance -= currentBet*2;
alert(getBalance());
$("img").css("border","");
}
The problem is that getElementsByTagName() returns a collection not one element.
First you need to iterate over the collection of html elements you have - when using getElementsByTagName you get back an array of elements.
Second you need to give the elements a style of zero.
const divElements = document.getElementsByTagName("IMG");
for (let i=0; i < divElements.length; i++) {
divElements[i].style.border = 0;
}
You can see the code on stackbliz -
https://stackblitz.com/edit/border-issue?file=index.js

How do I hide the closest element to the element that was clicked without jQuery?

I have a function that changes the src attribute of an icon when this one is clicked.
I also want it to hide the closest icon of the class fave_icon. I tried the following but it's not working:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png")
{
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest(".fave_icon");
heart.style.visibility = "hidden"
}
}
Basically I want to hide the closest element with class fave_icon to trashcan.
On the HTML I have this several times:
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
If fave_icon is a class then you have to place dot (.) before the class name as part of the selector.
Change var heart = trashcan.closest("fave_icon");
To
var heart = trashcan.closest(".fave_icon");
Based on the code and HTML you have provided you can do something like the following:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png"){
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest('button').querySelector('.fave_icon');
heart.style.visibility = "hidden";
}
}
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
From the trash icon, you go up a level to the div, select the previousElementSibling to get the heart's div, and then go down a level to the heart image itself.
Because the element is already included in the event target, you don't need to pass this. Or, even better, if you select the trash image first, you can avoid this entirely and use explicit variable names, which are easier to understand and debug.
But inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Another problem is that buttons should not have closing tags. Use a container element instead, like a div.
So, try something like this:
document.querySelectorAll('img[src="Iconos/tacho.png"]').forEach(img => {
img.onclick = () => {
const heartImg = img.parentElement.previousElementSibling.children[0];
heartImg.style.visibility = 'hidden';
};
});
<div class="accordion">
<div>
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" alt="Delete" class="delete_icon">
</div>
</div>
you can add a class to the clicked element and use the general sibling combinator if the two items are adjacent.
document.getElementById("hide")
.addEventListener("click", (event) => {
event.target.classList.add('active');
}, false);
#hide.active~.element {
visibility: hidden;
}
#hide {
cursor: pointer;
}
.accordion {
padding: 15px;
background: lightgrey;
border-bottom: 1px solid grey;
}
.accordion div {
color: black;
margin-right: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/icono/1.3.0/icono.min.css" rel="stylesheet" />
<div class="accordion">
<div class="icono-trash" id="hide"></div>
<div class="element icono-heart"></div>
</div>

Can't hide other elements while clicking on another

I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}

stuck with onclick tried google couldn't find answer

i need help getting this to work, tried everything google had to offer.. but still stuck. what i need it to do is load the value of (div id="availablecredits") to (div id="beta") on click. can any body help me out?
onclick="javascript:document.getElementById('beta').value=(javascript:document.getElementById('availablecredits').value)"
i also tried onclick="javascript:document.getElementById('beta').value=('#availablecredits')"
The property value is common for input elements like <input>, <select>, <textarea> and <button>
I think what you want is to copy a content of a <div> element to another div. If it's the case, use innerHTML instead of value.
Here is a snippet, just click on the gray area.
#div-two {
min-height: 20px;
background: #CCC;
}
<div id="div-one">
Hello this is #div-one
</div>
<div id="div-two" onclick="document.getElementById('div-two').innerHTML=document.getElementById('div-one').innerHTML"></div>
SNIPPET #2
You've defined a third <div> which you use as trigger but you can't click it if it's not visible, because it's height is 0. Specify some text inside it, then it's visible and the JS part work. Take a look at the snippet.
#getCredits {
background: #CCC;
}
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits" onclick="document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML">Click here to get available credits</div>
SNIPPET #3 - jQuery
$('#getCredits').click(function() {
$("#beta").html($('#availablecredits').html());
});;
#getCredits {
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
Simple javascript function, change the ids in the function call to those of the elements in question.
<script>
function set_value( src,tgt ){
document.getElementById( tgt ).innerHTML=document.getElementById( src ).innerHTML;
}
</script>
<style>.p5{ display:block; padding:1rem; margin:1rem; border:1px solid black;}</style>
<div class='p5' id='src_div' onclick="set_value('src_div','tgt_div')">Weebles wobble but they don't fall down!</div>
<div class='p5' id='tgt_div'></div>
Or you can use a link to set the value
you should try to avoid writing inline event.try this:
<style>
#getCredits {
background: #CCC;
}
</style>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
<script>
document.getElementById('getCredits').addEventListener("click",function(){
document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML;
});
</script>
Why inline css and javascript are bad:http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
The .val() method is sometimes useful:
var input = $("#Input").val();

Determine HTML element position change

EDIT: See update!
I have the following html:
<body>
<span id="milestone1">
</span>
<img id="image1" src="blabla.jpeg" style="width:400px;height:200px;" />
<div id="divOverlayOverImage1" style="position:absolute; top:100px; left:40px; width:400px;height:200px;" onclick="DoFunkyStuff();"><div>
</body>
At first the divOverlayOverImage1 is positioned over Image1, covering it, but if I run the code below, the #divOverlayOverImage1 element will no longer covering the #image1 element.
$("#milestone1").after('<div style="width:500px; height:500px; background-color:blue;">');
I want to have an event that notifies me when #image1 changes its position, so I can update the position of #divOverlayOverImage1.
NOTE: I do not have full control over the dom. the $("#milestone1").after('<div style="width:500px; height:500px; background-color:blue;">'); command is run by a third party.
UPDATE: I do not have full control of the DOM, so I cannt put a callback to the element add function, as it is not me making this call.
Also, I cannot modify HTML like crazy. I just come to a set of websites, append and overlay to a specific image throung JavaScript and that's it. There are other competitiors that change the HTML as well.
If you have full control over the DOM, and I assume you have, you can add a call to every change you make in the DOM that will affect that <span>.
function yourFunction() {
$("#milestone1").after('<div style="width:500px; height:500px; background-color:blue;">');
updateMyOverlayPosition();
}
if that doesnt work, you might try this one here: Detect changes in the DOM
edit
if you want events:
$('#image').on('adjustOverlay',function(e) {
// adjust the position of the overlay
}
$("#milestone1").after('<div style="width:500px; height:500px; background-color:blue;">');
$('#image').trigger('adjustOverlay', {extra: "info", some: "parameters"});
edit2
Since you don't have full control over changes in the DOM and you can get surprised you can either go with the link I already provided above or check in an interval if the overlay is still where it needs to be. This doesn't solve the problem in the way you want it, but there is no native event on DOM-changes, so you have to stick with some sort of work-around.
var checkTime = 100; //100 ms interval
var check = setInterval(function() {
// adjust overlay position
}, checkTime);
edit3
next possible solution: if you know how affecting code is inserted in the DOM, you can try to change that method so that it always runs your adjustOverlayPosition() or fires an event, if you like events. Example: if it is inserted with jQuery's .after() you can modify that function:
jQuery.fn.extend({
// since the .after() function already exists, this will
// actually overwrite the original function. Therefore you need
// the exact code that was originally used to recreate it.
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
// call the function directly
adjustOverlayPosition();
// or call an event
$('#image').trigger('adjustOverlay', {extra: "info", some: "parameters"});
}
});
Drawback: this solution can be risky and works only if you know the code that is used originally. So it would also depend on the jQuery version.
One workaround is to reorganize your layout.
Wrap your image and overlay into a div. That way they will always remain that way.
<div id="wrap">
<img id="i1" src="..." />
<div id="overlay" />
</div>
#wrap {
position: relative;
width: 400px;
height: 200px;
}
#overlay {
position: absolute;
top: 100px;
left: 40px;
width: 400px;
height: 200px;
}
If wrapping the img with a ovelay is only your requirement, I think you can go with a pure css Solution:
Try the demo
HTML
<p id="milestone1">
First Overlay
</p>
<div class="img-overlay-container" style="width:400px;height:200px;">
<img id="image1" src="blabla.jpeg"/>
<div id="overlay1" onclick="alert('clicked');">
</div>
</div>
<p id="milestone2">
Second Overlay
</p>
<div class="img-overlay-container" style="width:100px;height:400px;">
<img id="image2" src="blabla.jpeg"/>
<div id="overlay2" onclick="alert('clicked');">
</div>
</div>
CSS
.img-overlay-container{
position: relative;
display:inline-block;
}
.img-overlay-container > img{
}
.img-overlay-container > div{
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
background: rgba(3,3,3,.1);
}
function changePosition(callback) {
$("#milestone1").after('<div style="width:500px; height:500px; background-color:blue;">');
callback();
}
Then you can call changePosition(function() {// Add your event handler function}).
Hope this will help you!

Categories