How to display a div/element on mouse hover using external JavaScript? - javascript

My divs are nested so i understand i cant display an element if its already hidden. I want the information(p1 inside my html code)to display once the mouse hovers over another element(h1 in my html. I have already made my paragraph 1 style to none in JavaScript, now i need it to re-appear, i have tried the following code to attempt to make it re-appear document.getElementById("1").onmouseover.style.display = "block"; but with no success.
This is My HTML code, ignore the order im new to web dev lol
This is the code i have tried but it doesnt seem to work
This is the end result i want, the circled text on hover display the paragraph

So a few things. For starters, put actual code into your questions instead of screen shots. If we can't reproduce your issue it's difficult to troubleshoot usually from just pictures.
Next, you might familiarize yourself with syntax a bit more since p1 isn't a valid HTML element.
Then, try not to rely on javascript too much and keep presentation stuff on the compositor thread. Here's an example accomplishing your goal with no javascript. Hope it helps, cheers!
p {
display: none;
}
h1:hover + p {
display: block;
}
<h1>Hover me</h1>
<p>PEEK A BOO!</p>

Yes, this is doable without javascript but since the question asked how to do it with, hopefully this helps get OP on the right track.
<div id="bioBlock" style="display:none">
<h2 id="1">
Cameron Lodge
</h2>
<p1 id="para">Im an avid learner of anything computers....</p1>
</div>
function showBioBlock() {
document.getElementById("bioBlock").style.display = "block";
}
https://jsfiddle.net/avL3j765/

document.getByElementId("myH1").onmouseover = function(){
displayH1("myP");
}
document.getByElementId("myH1").onmouseout = function(){
displayH1("myP");
}
function displayH1(myId){
if(document.getByElementId(myId).style.display == "block"){
document.getByElementId(myId).style.display = "none";
}else{
document.getByElementId(myId).style.display = "block";
}
}
This invokes a function that toggles the paragraph's style when the mouse enters and leaves the element. It assumes that you have an id on both your h1 and p tags, in my example myH1 and myP respectively.

Related

if statement that checks div condition

I have 5 different divs - they are all set to display: none;
When the user clicks, the divs become visible (display: block;)
I want to make an if statement that checks if the divs have a value of display: block; and once they do, I want another div to pop-up.
Is this possible? Very new to javascript and I'm trying to be creative and learn. Thanks in advance.
<div id="DivId">Block to check<div>
<div id="MessageBlock">Message to be gives</div>
<div onclick="runCode();">CLICK HERE</div> //user clicks on this and it runs code
<script>
function runCode(){
if(document.getElementById("DivId").style.display == "block")//Code checks if div "DivID is block"
document.getElementById("MessageBlock").style.display = "block";//Do something such as show message block
}
</script>
Hope this puts you in the right direction
Are you working with plain JavaScript, or you're using jQuery?
if (getComputedStyle(document.getElementById("div"))[display] === 'block')
document.getElementById("anotherdiv").style[display] = 'block';
Hope this helps

this.nextChild coming up undefined - mouseover/mouseout

I'm a student and still learning, so my apologies if this is a silly question. Normally I can figure this out by sifting through other questions here, but I seem to be stuck this time.
I'm just trying to do a simple mouseover/mouseout, where when you mouse over the image, the image disappears and the text in the anchor tag changes to the name of the link (ie. hover over the house icon and it disappears and is replaced by "HOME"). I got that part working fine, but I can't get it to switch back to the icon when the mouse leaves the link. This is the current HTML for the link:
<li class="linksLi">
<a id="#homeLink" data-namesrc="HOME" class="linksA">
<img src="img/home.svg" alt="Home Icon" class="links">
</a>
</li>
and then the javascript:
var linksImg = document.querySelectorAll(".links");
var linksName = document.querySelectorAll(".linksA");
function changeImg() {
this.classList.add("hide");
this.parentElement.innerHTML = this.parentElement.dataset.namesrc;
}
function changeName() {
this.innerHTML = "";
this.nextChild.classList.remove("hide");
}
for (var i=0;i<linksImg.length;i++) {
linksImg[i].addEventListener("mouseover", changeImg, false);
}
for (var j=0;j<linksName.length;j++) {
linksName[j].addEventListener("mouseleave", changeName, false);
}
changeImg() is attached to the img tag, and changeName() is attached to the anchor tag. But my issue is in changeName(), when I try to remove the class "hide" from the child, it tells me the child is undefined (even though the img tag is clearly inside the a tag in the HTML). I've seen a lot of stuff regarding nodes and whitespace that I don't entirely understand, so I have no idea if that's what the issue is? Maybe this is a really basic problem and I'm missing something really obvious, I have no idea, but any help would be greatly appreciated!
JAVASCRIPT ONLY PLEASE, no jQuery!
Try taking the event as a parameter to the functions and using "event.target" instead of "this"
function changeImg(evt) {
evt.target.classList.add("hide");
evt.target.parentElement.innerHTML = evt.target.parentElement.dataset.namesrc;
}
"this" is a tricky keyword in JavaScript which can be many things depending on how the function is called.
And a JSFiddle for you.
EDIT
I have updated the JSFiddle to add/remove a span instead of setting innerHTML.
Thank you for the answers! For anyone wondering, I also got it working by making the img and anchor tags sibling, rather than the img being a child of the anchor tag. That way I could just target nextSibling in the js, and the issue of innerHTML creating an empty anchor tag and removing the img was no longer a problem.

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

Click to show more - maybe JS?

I am not sure what language or how to do this, but I am looking to have a word on a page, and when clicked, it will reveal more underneath. If it is clicked again, that stuff will hide away again? Any ideas?
Basically, you will need to manipulate the display CSS property of the element to be hidden/revealed:
<span id="showHide">Show</span>
<div id="foo" style="display:none">Here is some text</div>
<script>
document.getElementById("showHide").onclick = function() {
var theDiv = document.getElementById("foo");
if(theDiv.style.display == 'none') {
theDiv.style.display = 'block';
this.innerHTML = 'Hide';
} else {
theDiv.style.display = 'none';
this.innerHTML = 'Show';
}
}
</script>
I'd recommend javascript and using jQuery .show() & .hide() methods:
http://api.jquery.com/show/
http://api.jquery.com/hide/
http://www.learningjquery.com/2006/09/slicker-show-and-hide
you could do this with jQuery, here a ready to use example:
http://jsfiddle.net/8sDLg/
$(function() {$('div.more').hide()
$('a.showmemore').click(function(){
$(this).next('div').slideToggle()
})})
Put the stuff in a div with style display:none;. In the onClick handler of the word (can be link or a button), toggle the display style between '' (which means 'default') and 'none'
I created a demo for you here.
You could use jQuery for that and make your life easy:
Show/Hide
<div id="mydiv">Some content</div>
jQuery:
$(function(){
$('#link').click(function(){
$('#mydiv').slideToggle();
return false;
});
});
As can be seen, the slideToggle() does the trick there for you :)
Executive summary: use a framework plugin
Long version:
You could use javascript -- more likely in a combination with a javascript framework, like jQuery. This would involve adding a click handler to the word (actually a span tag around it) and having a way to retrieve the extra information to show as a tooltip -- there are plenty of plugins for this. Search for "jquery tooltip" here or using google: here's one example.
Alternatively, you could simply surround the word with the span tag and add a title attribute to the tag. Hovering over the word (actually the tag) would bring up the browser's default tooltip. This might be an easy way to get started with it -- in fact, this could be the start of the javascript solution. Using the tag for the click event and taking the data from the title attribute -- probably by storing the title in jQuery data on page load, then grabbing the text from the data on click so that you don't have a conflict with the browser's tool tip behavior. Many of the plugins operate this way.
Another elegant approach using pure HTML and CSS without JavaScript.
HTML:
here goes text before
<label class="details">
<input type="checkbox" /><span>here come some details</span><em> </em>
</label>
and after
CSS:
.details input,
.details span {
display: none;
}
.details input:checked~span {
display: inline;
border-bottom: dotted 1px gray;
}
.details em:after {
content: "show...";
}
.details input:checked~em:after {
content: "...hide";
}
Quick idea how to do it when avoiding a JS-only solution. I'm using jQuery here, because it is faster to code in, but as I mentioned above, if this is your only JS functionality it would only add a heavy-weight file for some trivial extras.
<script type="text/javascript">
jQuery(function() {
$(".article .additional")
.hide()
.before("<a href='#'>")
.prev()
.text("more")
.click(function() {
$(this).next().toggle()
})
});
</script>
<div class="article">
<h2>Some headline</h2>
<p>Some intro text that is always visible</p>
<div class="additional">
<p>Some extra text that is hidden by JS</p>
<p>But will stay visible if the visitor doesn't have JS</p>
</div>
</div>
As you see, the HTML is completely stand-alone. Only if JavaScript is supported, a "more" link will be added and the additional content hidden, so that non-JS users still can read all the text and don't have an useless "more" link.

How can I create an element that flips between two values on click?

Given two spans like this:
<span>Click for info</span>
<span style="display: none">Here is a big long string of info blah blah</span>
...I'd like to have an onclick function attached to each so that the visitor sees "Click for info", and then when they click it, the first span is hidden and the second is unhidden. And, of course, when the second is clicked, things go back to the way they were originally.
I don't have a way of easily generating unique IDs, so I'd prefer to avoid the getElementByID() route, and I'd rather not use jQuery or any other heavyweight dependency. Is there an elegant way to do this?
The best idea I have so far is to write a toggleAllSiblings() function, set onclick to that function for both elements in the pair, and then wrap each pair in a parent element.
Can it be done without the parent node?
If you really want to go without ids you could do something like this:
<script>
function togglePrevious(sender) {
sender.previousSibling.style.display = "inline";
sender.style.display = "none";
}
function toggleNext(sender) {
sender.nextSibling.style.display = "inline";
sender.style.display = "none";
}
</script>
<span onclick="javascript:toggleNext(this);">Click for info</span>
<span onclick="javascript:togglePrevious(this);" style="display:none">Info blablabla</span>
And please not that you should really use "inline" instead of "block" if you are using spans as they are inline elements. Setting their display style to block will force them to be divs.
Yet another version, a la progressive enhancement — will properly show the full info when JavaScript is off.
<span class="details">Here is a big long string of info blah blah</span>
<script type="text/javascript">
// Open/close span behaviour
//
function infoToggle(span) {
var ersatz= document.createElement('span');
ersatz.appendChild(document.createTextNode('Click for info...'));
span.parentNode.insertBefore(ersatz, span);
span.style.display= 'none';
span.onclick= function() {
ersatz.style.display= 'inline';
span.style.display= 'none';
};
ersatz.onclick= function() {
ersatz.style.display= 'none';
span.style.display= 'inline';
};
}
// Bind to all spans with class="details"
//
var spans= document.getElementsByTagName('span');
for (var i= spans.length; i-->0;)
if (spans[i].className=='details')
infoToggle(spans[i]);
</script>
I'm not sure of the implementation, but the logic will look similiar to
Get all spans
Hide adjacent spans
beneath (leave them visible for non
JS users by default)
Attach even
handler to first spans
Event handler
function - show next span if next
span invisible, otherwise hide it
This is off the top of my head & untested. It should get you going at least.
<script>
function toggle(id)
{
var display = document.getElementById(id).style.display;
if ( display == "block" )
document.getElementById(id).style.display = "none";
else
document.getElementById(id).style.display = "block";
}
</script>
<span onclick="javascript: toggle('span_to_toggle');" id="clickable_span">click here</span>
<span id='span_to_toggle' style="diplay:none">foooooooooooooooooooooo</span>
quick rework of #Jason:
<script>
function toggle(targetId, sender)
{
var show = document.getElementById(targetId);
show.style.display = "block";
sender.style.display = "none";
}
</script>
<span onclick="javascript: toggle('more', this);" id="less">click here</span>
<span style="display:none;" id="more" onclick="javascript: toggle('less', this);" >foooooooooooooooooooooo</span>
Just as a side note for when you're developing javascript stuff which involves creating elements in the DOM. If you're not going to use something like jQuery (I'm not a fan of frameworks, too heavy and non-specific) try and use a function to make your elements for you, that way you don't have too many redundant lines as it tends to make your scripts really heavy.
I personally use a code snippet i found here www.dev-explorer.com/articles/create-dom-object but you might find something that suits you better. If your site downloads quicker the user doesn't have to wait as long for onload events etc and generally doesn't get annoyed as easily.
Hope this made sense
Thanks,
Scarlet
I'd rather not use jQuery or any other heavyweight dependency.
I don't know if that is a good approach. Unless you can attribute any real performance problem to using jQuery or prototype.js (which are both not really that heavy), you should use them.
Otherwise you will just spend a lot of time with repetitive typing and on fixing nasty browser bugs and incompatibilites.
I don't have a way of easily generating unique IDs
Again, you really want $$('div span[someParam=something]'). And since the libraries dispatch this to native browser query functions where available, it is probably not even slower than a hand-coded solution. Definitely more maintainable.

Categories

Resources