How to do things to a element on mouseenter? - javascript

how to execute something on mouse enter? like show in the code down below.
for(x=1; isset($_COOKIE["link$x"]); $x++)
echo <div id="'.$x.'" OnMouseEnter="myfunction('.$x.')">
}
and then in javascript
function myfunction(which){
// doing stuff on id with "which"
}

onmouseenter is specific to IE, so use onmouseover:
myElement.onmouseover = function()
{
document.getElementById(which).style.backgroundColor = 'red';
}
yes, it's as simple as that... notice I changed red to 'red', because I don't think you've defined red. This is how to do it in Javascript, though it would be much simpler to do it in CSS with :hover, but you're asking for Javascript.

If you just want to apply a style on mouseover, you don't need JavaScript. The CSS :hover pseudo-selector should work fine:
#elementId {
background: white;
}
#elementId:hover {
background: red;
}

You don't even have to go that far...
you can do this simply and easily using a :hover pseudo class.
in your css create two rules
.myHoverDiv
{
/* any styles you need here that show when not hovered over */
}
.myHoverDiv:hover
{
/* any styles here that should change when the mouse hovers over it */
background-color: red;
}
then on your tag use
<div class="myHoverDiv"> ... div inner contents here ... </div>
your div's style will change as expected when the mouse is hovered over it

As kumar_v asked too, i guess you shoud use "OnMouseOver" instead of "OnMouseEnter" to get a "hover"-effect.
So your PHP-code should be like that:
for($x=1; isset($_COOKIE["link$x"]); $x++) {
echo '<div id="'.$x.'" OnMouseOver="myfunction('.$x.')">test</div>';
}
and Javascript:
function myfunction(which){
document.getElementById(which).style.backgroundColor = "red";
}

better you handle your javascript in one block and I suggest you to make a handler to do that for you, if you use common javascript library such as jQuery and mouseover, that becomes super easier to handle and debug, remember add jQuery library to head of page.
server-side:
echo '<div id="handler_id">';
for(x=1; isset($_COOKIE["link$x"]); $x++)
echo <div id="'.$x.'">
}
echo '</div>';
client-side, this part is in within <script /> tag or in separated js file:
(function(window, $) {
var window.handler = handler = {
init: function() {
$('#handler_id > div').mouseover(function(){
console.log("mouse is over", this);
});
}
}
$(function(){ handler.init(); });
})(window, jQuery)

Related

Is there a way to have active/inactive state on a single link?

I will need to put 2 different actions on a single link which would have an active/inactive state, right now I only know how to do one at the time, something like this (active):
State One
And I would like to have another one on same click (inactive), is there a way to have this dynamically changed? The label shouldn't change, except for color for example - style.
On the other side, it would be a great thing if I could show the list of active items as well, something like:
Active states: State one, State two, State ...
I recommend something other than an A tag for what you're doing. I also recommend the modern equivalent of an onclick, an event listener. I also recommend assigning and toggling the class.
State One
I have removed your onclick and put it into an event listener. I've added a class, so you can toggle it.
function classToggle() {
this.classList.toggle('class123');
this.classList.toggle('class456');
}
This toggles your class, thus allowing you to change the behavior of the link based on the class. Active/Inactive or Class123/Class456 whatever you want to use will work.
document.querySelector('#myDiv').addEventListener('click', classToggle);
This is your listener. It applies the classToggle function on click. You can do this with a div/button/whatever. Personally I'd change the A tag to a Div.
<div id="myElem" class="class123">click here</div>
And here is an example of this stuff working and changing based on the toggle and classes.
function classToggle() {
this.classList.toggle('class123');
this.classList.toggle('class456');
}
document.querySelector('#myElem').addEventListener('click', classToggle);
document.querySelector('#myElem').addEventListener('click', mogrify);
function mogrify(){
if (document.querySelector('#myElem').classList.contains('class123')) {
document.querySelector('#myElem').style.backgroundcolor = "#54C0FF"
document.querySelector('#myElem').innerText = "State Two";
} else {
document.querySelector('#myElem').style.backgroundcolor = "#FF8080"
document.querySelector('#myElem').innerText = "State One";
}
}
.class123 {
color: #f00;
}
.class456 {
color: #00f;
}
State One
I think I got it to work, here's my code, please let me know if good enough.
A href:
State One
js:
<script>
function toggleState(a) {
if ( a.className === 'visible' ) {
HideOneState('state_One', gameInstance);
a.className = '';
} else {
ShowOneState('state_One', gameInstance);
a.className = 'visible';
}
}
</script>
#shandoe2020 has a good answer but here is the "old way" which is pretty easy to understand too. It can be adapted to links (or anything else) quite easily.
<!DOCTYPE html>
<html>
<head>
<style>
.my-button { width:150px; height:150px; }
.my-red { background-color:#ff0000; }
.my-blue { background-color:#0000ff; }
</style>
<script>
/* toggle the state of my-red and my-blue class */
function toggle()
{
/* yeah yeah, hardcoding the item to change is bad */
var elem = document.getElementById("btn")
elem.classList.toggle("my-red")
elem.classList.toggle("my-blue")
}
</script>
</head>
<body>
<div>
<p><button id="btn" class="my-button my-red" onclick="toggle()">Button</button></p>
</div>
</body>
</html>

Disable/Enable CSS on webpage using Javascript

According to This page I was able to remove all the CSS preloaded and added on the webpage using that. I wanted to implement a button system where "onclick" = enable/disable webpage CSS even the ones pre-loaded by my web-host. I would like to eliminate the style tags to prevent lags for my website users. I prefer using the script that I have linked above unless there is another alternative that works better. Is it possible to enable CSS onclick the same button to disable? If not is it possible, can it be done with this quick? example with the preferred script below:
if (disable) {
style = "disable";
} else {
location.reload();
}
PREFERRED SCRIPT:
function removeStyles(el) {
el.removeAttribute('style');
if(el.childNodes.length > 0) {
for(var child in el.childNodes) {
/* filter element nodes only */
if(el.childNodes[child].nodeType == 1)
removeStyles(el.childNodes[child]);
}
}
}
removeStyles(document.body);
What about a different aproach?
Add initially a class to a body called 'styled' for example
<body class="styled">
use it as a main selector in your css definitions
<style>
.styled a { ... }
.styled h1 { .... }
</style>
then an example jquery script to toggle the class:
<script>
$(function() {
$('#myswitch').click(function() {
$('body').toggleClass('styled');
});
});
</script>
when class is present, the page will be styled, when absent there will be no styling.
Of coures there could be better aproach, but this is the first thing which pops up in my mind
To remove all style on an element, you could do
function removeStyles(el) {
el.style = {};
}
If you want to enable/disable the CSS on the page, then the goal is not to merely remove all the styles on the page, but you will need to save them somewhere also so they can be recalled when the user re-clicks the button. I would recommend having jQuery to help you with this, and it could be done the following way:
var style_nodes = $('link[rel="stylesheet"], style');
style_nodes.remove();
$('*').each(function(num, obj) {
var style_string = $(obj).attr("style");
if (style_string) {
$(obj).data("style-string", style_string);
$(obj).attr("style", "");
}
});
Now you've saved the stylesheets and style DOM nodes inside of style_nodes, and the actual style attribute inside of a jQuery data attribute for that specific DOM node. When you click to add the CSS back to the page, you can do the following:
$('head').append(style_nodes);
$('*').each(function(num, obj) {
if ($(obj).data("style-string"))
$(obj).attr("style", $(obj).data("style-string"));
});
Check out this JS Fiddle I put together to demonstrate it:
https://jsfiddle.net/5krLn3w1/
Uses JQuery, but I'm sure most frameworks should give you similar functionality.
HTML:
<h1>Hello World</h1>
Turn off CSS
Turn on CSS
JS:
$(document).ready(function() {
$('a#turn_off').click(function(evt) {
evt.preventDefault();
var css = $('head').find('style[type="text/css"]').add('link[rel="stylesheet"]');
$('head').data('css', css);
css.remove();
});
$('a#turn_on').click(function(evt) {
evt.preventDefault();
var css = $('head').data('css');
console.info(css);
if (css) {
$('head').append(css);
}
});
});
CSS:
body {
color: #00F;
}
h1 {
font-size: 50px;
}

Add class on div mouse enter mouse leave and click

What i am trying to achieve is, i want to make it work like star rating. When you enter mouse star becomes yellow, when you leave mouse it turns gray and then if you click it again becomes yellow.
Not getting how to achieve it, I have added code to show you what i have tried so far.
JSfiddle
$(".na").hover(
function () {
$(this).addClass("clickstar");
},
function () {
$(this).removeClass("clickstar");
}
);
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
.clickstar{
background: #00A1EF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="na" style="border:1px solid #c0c0c0;border-radius:50%;width:115px;height:115px;display:inline-table;margin-right:5px;"></div>
You should consider using 2 different classes, .hoverstar and .clickstar, then :
http://jsfiddle.net/xLxbw216/1/
You would have one class for each case, which seems more logical ?
You can also make it simpler by removing .hover() method, and do it with CSS :
http://jsfiddle.net/xLxbw216/8/
I probably choose the second one, even if the first solution seems to be more "readable".
You can do it like this:
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
Fiddle Example
You should use a different class for permanent start and hover star
I have created a working example in JSfiddle
$(".na").hover(
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$this.addClass("clickstar");
}
},
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$(this).removeClass("clickstar");
}
}
);
$(".na").on("click",function(){
$(this).toggleClass("permstar");
});
add/remove class on hover events was conflicting with on click event, so i have moved the hover functionality to css
css:
.clickstar{
background: #00A1EF;
}
.na:hover{
background: #00A1EF;
}
live demo:
http://jsfiddle.net/dreamweiver/xLxbw216/7/
Happy Coding :)

jquery/javascript - how to "undo" a click event using if statement?

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.
<script>
$(document).ready(function() {
$("p, h1").click(function() {
$(this).css("background-color", "red");
if ($(this).css("background-color", "red")) {
$(this).css("background-color", "null");
}
});
});
</script>
First you need to use the getter version of .css() like
if($(this).css("background-color") == "red"){
but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.
So the solution is to use a css based solution using toggleClass()
.red {
background-color: red;
}
then
$(document).ready(function() {
$("p, h1").click(function() {
$(this).toggleClass("red");
});
});
Demo: Fiddle
$('p, h1').click(function() {
var $this = $(this);
var altColor = $this.data('altColor');
$this.css('background-color', altColor ? '' : 'red');
$this.data('altColor', ! altColor);
});
This answers your question, but you should really be using a CSS class for this.
This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:
CSS
p, h1 {
background-color: none;
}
p.red, p.h1 {
background-color: red;
}
JavaScript:
$('p, h1').click(function() {
$(this).toggleClass('red');
});

how to make javascript function call two divs

i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}

Categories

Resources