I would like to achieve the same effect found on the following website:
http://www.kpf.com/projectlist.asp?T=4
On mouseover of an image, the corresponding text highlights and vice versa.
I've found a JavaScript solution on a forum. I've copy-pasted the solution below:
div code
<div style="width:400;height:500;" onmouseover="hightlight()" onmouseout="removehightlight()"><span id="textspan" >This is a test div to show mouseover</span><img id="imgsrc" src="/images/test.gif" /></div>
javascript
<script language="javascript">
function hightlight()
{
document.getElementById("textspan").style.color = "blue";
document.getElementById("imgsrc").style.border = "1px solid blue";
//document.getElementById("textspan").setStyle("color","blue");
//document.getElementById("imgsrc").setStyle("border","1px solid blue");
}
function removehightlight()
{
document.getElementById("textspan").style.color = "black";
document.getElementById("imgsrc").style.border = "0px solid blue";
}
</script>
However, this solution is for an image and text in the same div. My image and text reside in two separate divs like so:
javascript
function hightlight()
{
document.getElementById("textspan").style.text = "underline";
document.getElementById("imgsrc").style.border = "5px solid #005596";
}
function removehightlight()
{
document.getElementById("textspan").style.text = "none";
document.getElementById("imgsrc").style.border = "5px solid white";
}
text
<div id="left-menu" >
<div align="right">
<p><!-- #BeginLibraryItem "/Library/left-projects-category.lbi" --> <span class="left-title">Category</span><!-- #EndLibraryItem --><br />
<span class="left-sub">Residential</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 Gurney Drive</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">78 LAD</span><br />
</p>
</div>
</div>
image
<div style="float:left; margin:90px 0 0 305px; padding:0 0 100px 0; height:auto;">
<img src="../../images/completed-projects/thumbnails/11-gurney-drive.jpg" width="215" height="170" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
<img src="../../images/completed-projects/thumbnails/78-lad.jpg" width="215" height="171" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
/div>
MY PROBLEMS
Let's call 11 Gurney Drive - Text1 and 11-gurney-drive.jpg - Image1
78 LAD - Text2 and 78-lad.jpeg - Image2.
My problems:
On Text1 mouseover, it highlights both Text1 and Image1 - Good.
On Text2 mouseover, it highlights Text2 and Image1 - it should highlight Text2 and Image2.
On Image1 mouseover, it highlights only Image1 - it should highlight Text1 and Image1.
On Image2 mouseover, it highlights only Image1 - it should highlight Text2 and Image2.
I have very little experience in customising Javascript; have tried Googling getElementbyId but it all might as well be in Greek.
Edit
I forgot to mention that I've tried adding a 2nd unique element ID called textspan2 and imgsrc2 but that didn't seem to work. What I did:
javascript
function hightlight()
{
document.getElementById("textspan").style.text = "underline";
document.getElementById("imgsrc").style.border = "5px solid #005596";
document.getElementById("textspan2").style.text = "underline";
document.getElementById("imgsrc2").style.border = "5px solid #005596";
}
function removehightlight()
{
document.getElementById("textspan").style.text = "none";
document.getElementById("imgsrc").style.border = "5px solid white";
document.getElementById("textspan2").style.text = "none";
document.getElementById("imgsrc2").style.border = "5px solid white";
}
text
<div id="left-menu" >
<div align="right">
<p><!-- #BeginLibraryItem "/Library/left-projects-category.lbi" --> <span class="left-title">Category</span><!-- #EndLibraryItem --><br />
<span class="left-sub">Residential</span><br />
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 Gurney Drive</span><br />
<span id="textspan2" onmouseover="hightlight()" onmouseout="removehightlight()">78 LAD</span><br />
</p>
</div>
</div>
image
<div style="float:left; margin:90px 0 0 305px; padding:0 0 100px 0; height:auto;">
<img src="../../images/completed-projects/thumbnails/11-gurney-drive.jpg" width="215" height="170" id="imgsrc" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
<img src="../../images/completed-projects/thumbnails/78-lad.jpg" width="215" height="171" id="imgsrc2" style="border:5px solid white" onmouseover="hightlight()" onmouseout="removehightlight()"/>
/div>
getElementById is one of those calls that actually does what it says. :-) It gets a DOM element by its id attribute. Since id must be unique, it gets you one specific element that you can then interact with (for instance, setting its style properties).
So part of your problem is that you have two elements with the ID "textspan", and two elements with the ID "imgsrc", which means the browser will do something undefined because you can't do that.
Within an event handler, this will point to the element that you've put the handler on. So in your highlight and removeHighlight functions, you can use this (rather than getElementById) to get a reference to the img DOM elements. That just leaves the text ones.
You could use a naming convention ("textspan1" and "imgsrc1", "textspan2" and "imgsrc2" for instance), so the handlers would look like this:
function hightlight()
{
var textid = this.id.replace("imgsrc", "textspan");
var text = document.getElementById(textid);
text.style.color = "blue";
this.style.border = "1px solid blue";
}
function removehightlight()
{
var textid = this.id.replace("imgsrc", "textspan");
var text = document.getElementById(textid);
text.style.color = "black";
this.style.border = "0px solid blue";
}
...or you might use an attribute (say, data-text) on the img tags that gives the ID of the text field linked to it; you can get an attribute from a DOM element like this:
var textid = this.getAttribute("data-text");
Custom attributes are invalid in HTML4 and below, but I've never met a browser that had a problem with them. In HTML5 and above, you can have custom attributes as long as they start with data- as above. So if validation is part of your working practices (and it's usually a good idea), you might consider starting to use the HTML5 doctype unless you have a particular reason for staying with the previous one (like, for instance, you're uncomfortable using a doctype for a version of HTML5 that hasn't even reached candidate recommendation stage yet). A lot of us are happy enough to go ahead now.
this is not the element the way you're hooking up the handlers. I'd forgotten, it's been a long time since I used the DOM0 way of hooking up handlers (onmouseover=). But the below works:
Or, because of the way you're attaching the handlers, you could pass an argument into the functions telling them which one they're dealing with:
function hightlight(index)
{
var img = document.getElementById("imgsrc" + index);
var text = document.getElementById("textspan" + index);
text.style.color = "blue";
img.style.border = "1px solid blue";
}
function removehightlight(index)
{
var img = document.getElementById("imgsrc" + index);
var text = document.getElementById("textspan" + index);
text.style.color = "black";
img.style.border = "0px solid blue";
}
...where your onmouseover and onmouseout attributes changes to:
onmouseover="hightlight(1);" onmouseout="removehightlight(1);"
onmouseover="hightlight(2);" onmouseout="removehightlight(2);"
Here's a live example.
Side note: The code you've found is using the mouseover and mouseout events. Be aware that those don't quite do what you may expect they do, and it can bite you, although the specific way you're using them is mostly fine (you're doing more work than necessary, but that's okay). But suppose your markup changed a little:
<span id="textspan" onmouseover="hightlight()" onmouseout="removehightlight()">11 <strong>Gurney</strong> Drive</span><br />
Now there's an element within the span that you're watching those events on. That means that as the user's mouse travels from left-to-right, you'll see a series of mouseover events as the mouse travels over the text "11(space)", then your code will see a mouseout event as the mouse moves over into the word "Gurney". Why does this happen? Because the mouse has moved out of the span and into the strong element. Then it will immediately see another mouseover, because the mouse is moving over the strong element and the mouseover event bubbles up the DOM, so we see it on the span. This may cause flicker as the mouse moves into and out of the strong element.
Internet Explorer has the mouseenter and mouseleave events, which are more suited to what you're doing — but who wants to use events that are limited to only one brand of browser? Well, most good JavaScript libraries emulate these events even on browsers that don't support them natively, which brings me to...
Off-topic 1:
If you're just starting out with JavaScript on browsers, a word of warning: There are a number of browser inconsistencies and awkwardnesses (if that's a word) that libraries like jQuery, Prototype, YUI, Closure, or any of several others can smooth over for you. For what you're doing in this question, enh, they wouldn't bring a huge amount of value. But for more complicated stuff, they can save you a lot of time and trouble, leveraging the good work many others have done before you. Like, for instance, emulating mouseenter and mouseleave on browsers that don't support them. :-) I know for a fact both jQuery and Prototype do that for you, and I suspect others do as well.
Off-topic 2:
It's "highlight", not "hightlight". If someone needs to come maintain your code later, that typo (which is consistent, and so not a bug!) might well trip them up. Separately, the standard practice (which you're free to ignore!) is to camelCase words in function names, so removeHighlight rather than removehightlight. FWIW.
Related
So I'm having a really strange issue with the cursor. Basically, my menu allows keyboard navigation, so whenever a key is pressed, it will hide the cursor.
This works great (left screenshot) but when I have the mouse immediately over the menu itself, the cursor does not hide, despite the body showing inline style of cursor: none.
http://i.imgur.com/1VvS3H2.png
Here is the code that hides the cursor:
onKey(event: KeyboardEvent) {
var key = event.keyCode;
//User hit an arrow key, so we can assume they want to navigate using the arrows.
//Remove the mouse, until the mouse is moved again.
if (key == 38 || key == 40 || key == 8 || key == 13)
{
document.body.style.cursor = 'none';
this.mouseHidden = true;
}
...
}
Here is the code that returns it:
onMouseMove()
{
if (this.mouseHidden) {
this.mouseHidden = false;
document.body.style.cursor = 'default';
}
}
And here is my menu template:
<div id="menuContainer" *ngIf="!this.displaySplash" (mousemove)="onMouseMove($event)">
<div id="menu" class="cl-effect-1">
<div id="menuHeader">
<h1>{{gameName}}</h1>
</div>
<div id="menuContents" #menuContainer>
<div id="homeMenu" *ngIf="this.displayHome" #homeMenu>
<button class="mainmenu-button" id="play-button" (click)="pressedPlay()" (mouseover)="onMouseEnter($event)">Play</button>
<button class="mainmenu-button" id="music-button" (click)="pressedMusic()" (mouseover)="onMouseEnter($event)">Music</button>
<button class="mainmenu-button" id="credits-button" (click)="pressedCredits()" (mouseover)="onMouseEnter($event)">Credits</button>
<button class="mainmenu-button" id="exit-button" (click)="pressedBack()" (mouseover)="onMouseEnter($event)">Exit</button>
</div>
<div id="soundMenu" *ngIf="displaySound" #soundMenu>
<button class="mainmenu-button" id="mute-button" (click)="pressedMute()" (mouseover)="onMouseEnter($event)">Mute</button>
<button class="mainmenu-button" id="volUp-button" (click)="pressedVolUp()" (mouseover)="onMouseEnter($event)">Volume +</button>
<button class="mainmenu-button" id="volDown-button" (click)="pressedVolDown()" (mouseover)="onMouseEnter($event)">Volume -</button>
<button class="mainmenu-button" id="back-button" (click)="pressedBack()" (mouseover)="onMouseEnter($event)">Back</button>
</div>
<div id="creditsMenu" *ngIf="displayCredits" #creditsMenu>
<p class="mainmenu-text">Author: Kilo Mike Software</p>
<p class="mainmenu-text">License: Open Source</p>
<p class="mainmenu-text">Music License: Public Domain</p>
<button class="mainmenu-button" id="back-button" (click)="pressedBack()" (mouseover)="onMouseEnter($event)">Back</button>
</div>
</div>
</div>
I'm not sure what else to include, because I honestly have no idea as to why this is happening.
Any help would be much appreciated!
Cheers.
Edit: Oh, you can view the problem here: https://steamboatt.github.io/gravity/
Source Code: https://github.com/Steamboatt/gravity
You seem to be wanting to hide the cursor in your entire website.
I'd like to start by outlining this is regarded, in general, as a poor design decision, in terms of usability and accessibility. First of all, this can be done entirely with CSS and it is the recommended way to go about it. So, first, please remove all scripts related to hiding the cursor as they will most likely interact with the method I'm about to propose, rendering it ineffective.
body {
cursor: none;
}
should do the trick, in theory.
But most browsers, exactly for the reasons outlined above, have stronger rules applying to html elements designed for pointer interaction, when it comes to the cursor property. Namely, for <button>s. This is why you will need a stronger CSS rule applying. As in:
body *, body button {
cursor: none !important;
}
If you don't want this applying on all your elements, feel free to replace body with a more specific selector.
Looks like you need some CSS:
body.hide-cursor * {
cursor: none;
}
document.body.className = 'hide-cursor';
//or
document.body.className = '';
My goal, essentially, is to have the CSS :hover replaced by JavaScript. The reason is that I need a loop to be executed on a variable number of divs that will be nested inside the parent div that should react upon :hover.
The problem, however, is that I have no idea how to target just the div being hovered over without hard-coding in specific IDs - something that I will not be able to do once applied to my project, a tumblr theme.
HTML
<div id="motherbox">
<div class="middlebox">
<div class="childbox">One</div>
<div class="childbox">Two</div>
<div class="childbox">Three</div>
</div>
</div>
<div id="motherbox">
<div class="middlebox">
<div class="childbox">One</div>
<div class="childbox">Two</div>
<div class="childbox">Three</div>
<div class="childbox">Four</div>
<div class="childbox">Five</div>
</div>
</div>
CSS
#motherbox {
width:30%;
height:100px;
margin:100px auto;
background-color:gray;
}
JavaScript
document.getElementById("motherbox").onmouseenter = function(){
this.style.backgroundColor = 'blue';
};
document.getElementById("motherbox").onmouseleave = function(){
this.style.backgroundColor = "gray";
};
JSFiddle
My question is - how do I cause divs with the same class or id to react individually (or, rather, not all at once) on hover using javascript, rather than CSS?
Thank you for your time.
Basically you can select elements having a particular class using getElementsByClassName.
Here is a working demo.
var elements = document.getElementsByClassName('childbox');
for(var i=0; i<elements.length; i++) {
elements[i].onmouseleave = function(){
this.style.backgroundColor = "blue";
};
}
So use instead of getElementById this:
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
And provide classess for your divs, where you want have that event.
I try to paste text into multiple fields, but the formatting is only cleared on the first element, not the second etc.
I found this question https://stackoverflow.com/a/12028136/3955607 which works fine, but again, on multiple elements it doesnt work.
So I got this HTML
<div style="color:red">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
and this javascript:
document.querySelector("div[contenteditable]").addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
I have this fiddle http://jsfiddle.net/tdjuc8es/
just copy and paste the Some rich HTML- text and see what happens
Someone who can help me out?
document.querySelector yields one element. You want to use document.querySelectorAll to get all matching elements, and then iterate over that collection.
var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
editors[i].addEventListener('paste', myCustomPasteFunction);
}
Fiddle
If you're used to jQuery, you might think that document.querySelector() fulfils the same kind of function; however, it only returns the first element that matches the selector; instead you should have used document.querySelectorAll() and then used iteration to add your event handlers.
Since you've tagged it as jquery, you could also consider this:
$("div[contenteditable]").on("paste", function(e) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
div[contenteditable] {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="color:blue">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
I'm using e.originalEvent here because the one that jQuery passes you in the event handler is a wrapper object.
It is beacause the document.querySelector only return the first matched element.
You can use document.querySelectorAll instated.
Wish it can help you.
I've been experiencing a really bizarre issue with IE9 and IE10 (Win7 only).
If an HTML element (button, span, anchor) has an attached click listener which removes itself (or it's container) from the DOM--and then at a later point some other event (e.g: reset) adds the element back, the element still remains in ':hover' state, even without the mouse hovering on the element.
WHY does IE 9 & IE10 (Win7) do this? Also, is there a workaround, without resorting to some setTimeout async call?
Take a look at this JSBin: IE hover/active on remove/add
Code from JSBin
<div id="outer" style="border: 2px solid green; padding: 10px;">
<div id="container" style="border: 2px solid black; padding: 5px;">
<button id="button">Hide Me</button>
</div>
</div>
<button id="reset" style="margin-top: 20px">Reset</button>
And the JS:
var outer = document.getElementById('outer');
var container = document.getElementById('container');
var button = document.getElementById('button');
button.addEventListener('click', function() {
outer.removeChild(container);
}, false);
var reset = document.getElementById('reset');
reset.addEventListener('click', function() {
outer.appendChild(container);
}, false);
I'm leaning towards this being a bug in IE were if the element is removed from the DOM the styles aren't being refreshed correctly. However it seems that if you remove the container div as per below the :hover issue is fixed in IE.
I know you said without the use of setTimeout, but I haven't been able to make something else work.
button.addEventListener('click', function() {
window.setTimeout(function() {
outer.removeChild(container);
}, 1);
}, false);
I have a textarea that contains several images. All images have an id and I want to loop through all of those images and check if the need an onclick event (depends on id)
If the do not need a onclick event I need to check if the have one and remove it. If the need I I still need to remove it and add another (because the value of the onclick could be changed)
How can I do this?
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" onclick="loadSlideShow('7','open','3','','2')" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
<img id="slideShowImage_3" style="border: 1px solid black; cursor: pointer;" title="3" src="uploads/nieuws/7/1363788115.jpg" alt="3" />
http://jsfiddle.net/wmrqk/4/
Try this:
function cleanCode() {
var container = $('<div>' + $('#text1').val() + '</div>');
container.find('img').removeAttr('onclick');
$('#text2').html(container.html());
}
Demo
May not be cool, but you can do something like
function cleanCode() {
var els = $($('#text1').val());
els.each(function(i, v){
var $this = $(this);
if($this.attr('id') == 'slideShowImage_1'){
$this.removeAttr('onclick')
}
});
console.log($('<div></div>').append(els).html())
}
Demo: Fiddle
For a very simple HTML like the one you have here you could do this :
$('#text2').html($('#text1').html().replace(/onclick="[^"]*"/g,''));
But be very careful : parsing HTML in regex fails in general cases so you can only do that if you know where your HTML comes from and what it is like.
If your HTML is well formed, you can also do this :
var e = $('<div>'+$('#text1').val()+'</div>');
e.find('img').attr('onclick','');
$('#text2').html(e.html());
Demonstration
In any case, be aware that this couldn't be used as a security measure.