I want to change the src attribute of img inside of my span with id="slider_arrow",
<span id="slider_arrow">
<img />
</span>
each time my jquery function runs:
$("#0").click(function () {
/*Rest of the function*/
var arrow = document.getElementById('slider_arrow');
/*I want to add different slider_arrow's sprite each time i call this function*/
});
CSS:
.red_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") 0 0px;
}
.yellow_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") -26px 0px;
}
.black_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") -51px 0px;
}
My CSS Sprite file has 75px width and 12px of height. Each picture has 25px/12px.
The questions are:
1) Do I have correctly written CSS rules?
2) What I need to use to change src of img inside of span?
Thanks!
Fiddle: http://jsfiddle.net/vtkppwuc/3/
$("#0").click(function () {
var classes = ['red_arrow_sprite','yellow_arrow_sprite','black_arrow_sprite'];
var $span = $('#slider_arrow');
$span.attr('class', (classes[($.inArray($span.attr('class'), classes)+1)%classes.length]));
});
DEMO: http://jsfiddle.net/vtkppwuc/6/
Remove the image inside span and use jQuery for setting the css class to your Slider, try this code
<span id="slider_arrow" class="red_arrow_sprite">
</span>
$("#0").click(function () {
var item = $('#slider_arrow');
if (item.hasClass('red_arrow_sprite')){
item.removeClass('red_arrow_sprite').addClass('yellow_arrow_sprite');
} else if (item.hasClass('yellow_arrow_sprite')){
item.removeClass('yellow_arrow_sprite').addClass('black_arrow_sprite');
} else {
item.removeClass('black_arrow_sprite').addClass('red_arrow_sprite');
}
});
Related
Trying to change the background image of a div class background in CSS using javascript based on a hard-coded variable: See Function below:
<script type="text/javascript">
function checkLocation() {
var loctype="UH";
if(loctype=localonly)
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/LocalConn.jpg)";
else if(loctype=UH)
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/UHConn.jpg)";
else
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/MoodleUHConn.jpg)";
}
</script>
Called in HTML page see code below:
<div class="dropdown">
<button class="dropbtn"></button>
<div class="dropdown-content">
<div class="media">
<div class="media-left">
<script type="text/javascript">checkLocation();</script>
</div>
</div>
.CSS Code for the drop-down content class
/* The container <div> - needed to position the dropdown content */
.dropdown {
float: right;
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
right:0px;
margin-top:67px;
margin-right:20px;
background-color: #f9f9f9;
min-width: 125px;
height:150px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
background-image:url(../img/LocalConn.jpg);
}
Please help as this isn't working must be something staring at my face but can't figure any help appreciated??
These lines, e.g.
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/MoodleUHConn.jpg)";
need to have quotes inside url():
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url('./img/MoodleUHConn.jpg')";
Also, change this css
background-image:url(../img/LocalConn.jpg);
to
background-image:url('../img/LocalConn.jpg');
The problem is document.getElementsByClassName() will always return an Array of HTML elements. So, you need to apply style to the HTML element not the array. And localonly is undefined
Your <script> should be like this
<script type="text/javascript">
function checkLocation() {
var loctype="UH";
if(loctype=localonly)
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/LocalConn.jpg)";
else if(loctype=UH)
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/UHConn.jpg)";
else
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/MoodleUHConn.jpg)";
}
</script>
Your function should look like this:
function checkLocation(){
var loctype = "UH"; //if your setting variable (loctype) statically then there shouldn't be any logic, because it will always return TRUE for (loctype === "UH")
var image = (loctype === "UH") ? "url('./img/MoodleUHConn.jpg')" : (loctype === "localonly") ? "url('./img/LocalConn.jpg')" : "url('./img/MoodleUHConn.jpg')";
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage = image;
}
If your just trying to trigger the event, you don't need an <a> tag you can just use a <div> tag and attach an onclick event listener like so:
<div onclick="checkLocation()">Toggle Background Image</div>
also in your CSS the background-image: property in the .dropdown-content class needs quotes around the path like so:
background-image: url('../img/LocalConn.jpg');
I am trying to make a div .description that appears where the mouse is as it hovers over an element.
So far, I have this code for making the div appear in a fixed location:
$('.tooltip').mouseover(function(e) {
// var to link tooltips and hand to description
var target = $(this).attr('data-show');
// hide current description if showing
if ($('.description').is(':visible')) {
$('.description').fadeOut(0);
};
e.stopPropagation();
$('#' + target).fadeIn(400);
});
$('body').mouseover(function(){
$('.description').fadeOut(0);
});
It works fine, but instead of just have .description appear, I need it to appear where the mouse hovers.
I tried adding this function:
function divPosition (event){
// pass mouse position to description div css
$(".description").css({top: event.clientY, left: event.clientX- 200});
};
but it didn't work. I also tried adding the line within the function but i'm not sure how to pass the event argument.
Please see my JSfiddle: https://jsfiddle.net/bns4zp1q/2/
You can listen to the mousemove event, and use your divPosition function.
https://jsfiddle.net/agbuLop1/
$('.tooltip').mousemove(divPosition);
function divPosition (event){
// pass mouse position to description div css
$(".description").css({top: event.clientY, left: event.clientX- 200});
};
Does the description really have to follow the mouse movement or just appear at hovered circle? Here is a quick and dirty example without javascript:
https://jsfiddle.net/k9jpqom2/1/
(new) HTML:
<div class="tooltip-container">
<div class="image" id="machine1">
<img src="http://axevilw.sellamachine.com/EnhFiles/advert/182/Machine.jpg/Machine.jpg">
<div class="tooltip" id="tooltip1" data-show="description1">1
<div class="description-container">
<div class="description" id="description1">
LED Strip Lighting
</div>
</div>
</div>
</div>
</div>
(additional) CSS
.description-container {
width:1px;height:1px;position:relative;
}
#tooltip1:hover .description {
display:block;
width:10em;
position:absolute;
left:-4em;
height:auto;
}
.tooltip{
width:5%;
height: 6%;
}
If you don't want to edit the HTML you can try something like this:
https://jsfiddle.net/g2p5g2r4/2/
.tooltip .description-container {
width:1px;
height:1px;
}
#tooltip1:hover + .description-container #description1 {
display:block;
width:10em;
position:absolute;
height:auto;
top: 36%;
left: 25%;
}
#tooltip1 {
top: 31%;
}
You will have to fine tune the position of #description1, #description2, etc...
I have four lines of text and I want to display a specific image on mouseenter on the right side of each line.
The problem I'm having right now is that all four images are beeing displayed at the same time.
What am I doing wrong?
http://jsfiddle.net/m97qebjr/10
jQuery:
$(".thumb").hide();
$(".text" ).mouseenter(function() {
$(".thumb").show();
}).mouseleave(function() {
$(".thumb").hide();
});
You don't need jQuery at all: http://jsfiddle.net/m97qebjr/16/
.thumb {
display:none; /* added line */
float:right;
overflow:hidden;
width:100px;
height:100px;
}
.wrap:hover .thumb{ /* added rule */
display:block;
}
$(".thumb") matches all elements with class thumb. Try this instead:
$(".thumb").hide();
$(".text").mouseenter(function () {
$(this).siblings(".thumb").show();
}).mouseleave(function () {
$(this).siblings(".thumb").hide();
});
Updated fiddle: http://jsfiddle.net/m97qebjr/13/
I've got a bunch of images, on click I want the images to turn white emulating some kind of fade effect. So you click it and for 1 second it fades from the original image to just white. I also need it to turn back to the original image when the user clicks something else.
Is this possible with JavaScript? - If so what should I be looking at (I'm really bad with graphics).
I've had a go at trying this with opacity but I don't want the background to be visible behind the image
Psuedo-element Solution
You could use a wrapper with a pseudo-element to overlay what you're looking for -- and the animations are handled by a toggled CSS class (which is ideal for performance).
CodePen Demonstration
HTML
<div class="whiteclicker">
<img src="http://lorempixel.com/400/200" alt=""/>
</div>
SCSS
#import "compass/css3/transition";
body { background: gainsboro; text-align: center; }
.whiteclicker {
display: inline-block;
position: relative;
&::after {
content: "";
display: block;
position: absolute;
top:0; left:0; right:0; bottom:0;
background: white;
opacity: 0;
#include transition(opacity 1s ease);
}
&.active::after {
opacity: 1;
}
}
JS
$('.whiteclicker').click(function(){
$(this).toggleClass('active');
});
To ameliorate the Spencer Wieczorek solution (the way two seems to be the best solution on my opinion) :
What about creating the white div on the fly (and fade it in and out) instead of put it in the html code ?
See the fiddle.
$("#myImage").click(function(){
$(this)
.parent().css({position:'relative'}).end()
.after($('<div>')
.hide()
.css({position:'absolute'
, top: $(this).position().top
, left: $(this).position().left
, width: $(this).width()
, height: $(this).height()
, background: '#FFF'
})
.fadeIn('fast')
.on({
click : function(e){
$(this).fadeOut('fast', function(){ $(this).remove();});
}
})
);
});
Then, you don't have anything to add to the html code or in the css styles, Jquery does everything.
#Spencer Wieczorek : I did my own answer, because I did not agree with your way of designing the css style (the fixed position is really not good, especially if the page is scrolled for example...). Mine is more ... standalone-y ;)
You might want to try having two images stacked on each other.
See this:
<script type="text/javascript">
var image1 = '<img class="images" src="Image 1" onClick="switch();" />';
var image2 = '<img class="images" src="Image 2" onClick="switch();" />';
var currentImage = 1;
function switch(){
if(currentImage==1){
currentImage++;
document.getElementById("image").innerHTML = image2;
}
if(currentImage==2){
currentImage--;
document.getElementById("image").innerHTML = image1;
}
}
</script>
<style>
.images{ position:fixed; top: 0; left: 0; }
</style>
<img class="images" src="Black image" />
<div id="image"><img class="images" src="Image 1" onClick="switch();" /></div>
For the fade I'm just gonna see how you could do it.
EDIT:
<script type="text/javascript">
var fadecount = 100;
function fade() {
document.getElementById("imageToFade").style.opacity = fadecount;
fadecount--;
if(fadecount==0){
clearTimeout(fade);
}
}
function start_fade(){
var fade = setTimeout(fade(), 10);
}
</script>
With Base 64 you can just have the binary version of the picture and then an all white picture and based on the .click you reassign the src to the white base64...
document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="
just change to the all white version after the click, technically js driven from click event, and doesn't involve two different elements existing just at different layers...
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}