How to change the style of another element inline using javascript? - javascript

I would like to change the style of another inside a html element using javascript.
I have used the below code to change the current html element.
<p onmouseover="this.style.color = 'black;">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
I would like to change the other element's style inside the p tag using javascript.
can anyone help?

Using CSS you can achieve the same
<style>
p:hover + h1 {
background-color : red
}
</style>

This should be what you're after (not my work) - check out the fiddle link ...
<html>
<body>
<span id="div1" style="color:black;" onmouseover="stext()" onmouseout="htext()">TEXT1</span><p />
<hr color="black" />
<span id="div2" style="color:red;" onmouseover="htext()" onmouseout="stext()">Text2</span>
</body>
http://jsfiddle.net/FFCFy/16/

for example if you want to change the color:
<script>
document.getElementByTagName("p").style.color = "blue";
</script>
that should probably bound to an event, accordingly to what you want to do

use this :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<p style="color:red;" onmouseover="ch(event)">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
<script>
function ch(e) {
e.target.style.color = "black";
alert();
}
</script>
</body>
</html>

use with Javascript
function change(that){
document.getElementsByTagName('h1')[0].style.color="red";
}
<p onmouseover="change()">This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>
use with css
p:hover + h1{
color:red;
}
<p >This text should be changed</p>
<h1>How to change this element when hovered on p element</h1>

jQuery("p").mouseover(function(){
jQuery("h1").css("color", "yellow");
});

You can easily achieve it with jQuery:
$(function() {
$('#a-element').hover(function() {
$('#b-element').css('background-color', 'yellow');
}, function() {
// on mouseout, reset the background colour
$('#b-element').css('background-color', '');
});
});
If #b comes immediately after #a, the simplest solution is in pure css:
#a:hover + #b {
background: #ccc
}
If between #a and #b are other elements, you have to use ~ like this:
#a:hover ~ #b {
background: #ccc
}

Related

Why is the text getting appended to the wrong html element?

Overview: I have an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
$('#sample-div').append(tag);
}
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
Observation: I click on the button, the span element is added to the div as expected
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span>
</div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
However, after I start typing inside the div, I noticed the following:
<div id="sample-div" contenteditable="true">
<span class="tag">tag this is a continuation</span>
</div>
My expectation was:
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span> this is a continuation
</div>
So, my question is why the text "this is a continuation" also getting appended inside the span element? How do I achieve the one stated under my expectation?
The easiest solution would be to set the contentEditable attribute of your span to be false:
function addTags() {
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
Side note: since you are using jQuery you don't need to manually create the tag:
function addTags() {
var tag = '<span class="tag" contenteditable="false">tag</span>'
$('#sample-div').append(tag);
}

Javascript hide DIV HTML

Hey I can hide my divs but my problem is if I reload my page I always see the hidden div for one second.
Do someone know how to fix that?
To tackle this kind of issue, you need to have the <div> with an attribute hidden or something in the inline. Then you need to hide it with JS and the remove the inline thing.
$(function () {
$(".hide").hide().removeClass("hide");
});
.hide {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hide">I am not shown</div>
Method 2: Using hidden attribute.
$(function () {
$(".hide").hide().removeAttr("hidden");
});
.hide {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div hidden>I am not shown</div>
Method 3: Using hidden attribute and .prop().
$(function () {
$(".hide").hide().prop("hidden", false);
});
.hide {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div hidden>I am not shown</div>
In the CSS that you apply to your div, add:
display:none;
So the div will be loaded but invisible. When you need to you it, you can do as you are doing now
Just add hidden attribute to your div and it should fix your problem then remove it by javascript when you want to show it
$(document).ready(function() {
$('#myDiv').hide();
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="myDiv"><p>hello</p></div>
</body>
Yes you can create the div by javascript.
var div = document.createElement("Div");
var text = document.createTextNode("this is my Div")
div.appendChild(text);
document.body.appendChild(div);
<body>
</body>

Collapsible <div> onclick of link

I have something like the below:
$grabarticles = $db->prepare("
SELECT title, message
FROM articles
");
$grabarticles->execute();
foreach($grabarticles as $articles) {
echo $articles["title"];
//when a user clicks the text above, reveal the below
echo "<div id='article'><br/><br/>";
echo " ".$articles["message"];
echo "</div><br/><br/>";
//when a user clicks the $articles["title"] again, it then collapses
}
I'm not too well versed in Javascript to know, but is there some kind of thing I can do to make the $articles["title"] clickable, and onclick expand below to display the contents of $articles["message"], but also be reversible with another onclick? Here's an image to illustrate:
I want each <div> to be separate from another, so if I open #1 by clicking $article["title"] //1, and then open #2 by clicking the appropriate text, I can then close #1 by reclicking it without interfering with #2.
Wrap the article title in a DOM element that can have events bound to it, such as a span. Then give it a class so we can easily target it.
echo '<span class="article-title">', $articles["title"] ,'</span>';
Next, your id in your foreach loop should be a class, as you're generating multiple elements and only one element can have a single ID.
echo "<div class='article' style='display:none;'><br/><br/>"; // <--note the "class" instead of "id"
Now just make a click function to toggle the visibility of the element.
$('.article-title').click(function(){
$(this).next().toggle(); // find the next element after this one and toggle its visibility
});
Use jscript
<script type="text/javascript">
$(function () {
$('#testTitle').click(function (e) {
if ($("#testcontent").is(":visible")) {
$("#testcontent").slideUp("slow");
}
else {
$("#testcontent").slideDown("slow");
}
});
});
You want to use this collapsible DIV jQuery plugin written by John Snyder. It does exactly what you are looking for.
I use this on my blog you can see an example of it here and here
Sample HTML
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link href="/stylesheet.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.collapsible.js"></script>
<div class='collapsible'>
Header Text 1<span></span>
</div>
<div class='container'>
<div class='content'>
<div>
Body Text 1
</div>
</div>
</div>
<div class='collapsible'>
Header Text 2<span></span>
</div>
<div class='container'>
<div class='content'>
<div>
Body Text 2
</div>
</div>
</div>
</html>
CSS to go along with it
/* START SECTION FOR COLLAPSEIBLE DIV */
.collapse-open {
/* background:#000;
color: #fff;*/
}
.collapse-open span {
display:block;
float:left;
padding:10px;
background:url(/images/minus.png) center center no-repeat;
}
.collapse-close span {
display:block;
float:left;
background:url(/images/plus.png) center center no-repeat;
padding:10px;
}

How to change image to text using jquery's .hover event

I need a simple script that allows me to change the inner html of a p tag which in my case is an image to just plain text when I hover over it.
Example:
<div id="one">
<p><img src="events.png" alt="" /></p>
</div>
When i hover over the above p tag i want it to change to the text as seen below
<div id="one">
<p>Events</p>
</div>
You don't need to use javascript at all for this. This is handled very simply using css.
<div id="one">
<p>
<span>Events</span>
<img src="events.png" alt="" />
</p>
</div>
CSS:
#one p>span{ display:none; }
#one p:hover span{ display:inline; }
#one p:hover img{ display:none; }
Here's a fiddle of it in action: http://jsfiddle.net/CKpCk/
Try the following:
var html = $('#one p').html()
$('#one').hover(function(){
$('p', this).html('Events');
}, function() {
$('p', this).html(html);
})​
Demo
Try this one:
<html>
<head>
<title>Try</title>
</head>
<script type="application/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#testHover").hover(function()
{
$("#testHover").html("Events");
});
});
</script>
<body>
<div id="one">
<p style="width:200px;"id="testHover"><img src="events.jpg" alt="" /></p>
</div>
</body>
</html>

jQuery hover and class selector

I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
CSS:
.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
}
Javascript:
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
EDIT: I forgot to say that I had reasons not to want to use the css way.
And I indeed forgot to check if the DOM was loaded.
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)
HTML:
<div id="menu">
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
</div>
CSS:
.menuItem{
height:30px;
width:100px;
background-color:#000;
}
.menuItem:hover {
background-color:#F00;
}
test.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>jQuery Test</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
</body>
</html>
test.css
.menuItem
{
display: inline;
height: 30px;
width: 100px;
background-color: #000;
}
test.js
$( function(){
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
Works :-)
Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:
HTML:
<ul id="menu">
<li>Bla</li>
<li>Bla</li>
<li>Bla</li>
</ul>
CSS:
#menu {
margin: 0;
}
#menu li {
float: left;
list-style: none;
margin: 0;
}
#menu li a {
display: block;
line-height:30px;
width:100px;
background-color:#000;
}
#menu li a:hover {
background-color:#F00;
}
On a side note this is more efficient:
$(".menuItem").hover(function(){
this.style.backgroundColor = "#F00";
}, function() {
this.style.backgroundColor = "#000";
});
I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.
Don't forget to add display: block ; in .menuItem, so height and width are taken into account.
edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")
If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:
I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...
function changeAttr(attrName,changeThis,toThis){
var mysheet=document.styleSheets[1], targetrule;
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
targetrule=myrules[i];
break;
}
}
switch(changeThis)
{
case "height":
targetrule.style.height=toThis+"px";
break;
case "width":
targetrule.style.width=toThis+"px";
break;
}
}
I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery
http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/
Always keep things easy and simple by creating a class
.bcolor{ background:#F00; }
THEN USE THE addClass() & removeClass() to finish it up

Categories

Resources