I am using this code:
{ box-sizing: border-box; }
.specific:hover { background-image: url("example.jpg"); color:white }
With this code I am using this for html:
div class="specific"
With these I can easily hover over a paragraph and the background image appears instantly. But I want a little bit more like when I will hover, it should play a sound (namely mp3 file) and when I will move away the cursor the sound will stop playing and when I will hover my cursor again the sound should play from the first not from where I left it.
I have seen a lot of similar posts but the code there, I cannot put them into my file.
You can do this very easily with an HTML audio tag with the built in JS methods, properties etc. See this page. Many people don't like W3Schools much but there's good information there and it's very straight forward. It would take a very small amount of JS/jQuery utilizing a hover event listener with the .play() and .pause() methods to make this happen.
Here's a simple tutorial using .play() and .pause().
I laboriously put together a fiddle for you. But seriously, try your own stuff.
HTML
<div class="specific">
Listen to some <i>music</i>...
</div>
JS
let specific = document.querySelector(".specific");
let audio = document.createElement("audio");
audio.src = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
document.body.appendChild(audio);
specific.onmouseover = () => {
audio.play();
}
specific.onmouseout = () => {
audio.pause();
}
You're welcome.
UPDATE
Updated fiddle: https://jsfiddle.net/dLxkhogy/21/
HTML
<div class="specific">
<p>
Listen to some <i>music</i>...
</p>
</div>
<div class="specific">
<p>
Listen to some more music...
</p>
</div>
<div class="specific">
<p>
Listen to even <i>more</i> music!
</p>
</div>
JS
let specifics = document.querySelectorAll(".specific");
let audios = ["https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"];
for(i = 0; i < specifics.length; i++){
let specific = specifics[i];
let audio = document.createElement("audio");
audio.src = audios[i];
document.body.appendChild(audio);
specific.onmouseover = () => {
audio.play();
}
specific.onmouseout = () => {
audio.pause();
audio.currentTime = 0;
}
}
Related
I want the div "container" shows only after all image buttons in the div "inner" fully loaded. Or outer_1 and inner_1 show together after 1.jpg is loaded.
<div class="container" id="top">
<div class="outer" id="outer_1"><div class="inner" id="inner_1"><input type="image" src="1.jpg"></div></div>
<div class="outer" id="outer_2"><div class="inner" id="inner_2"><input type="image" src="2.jpg"></div></div>
<div class="outer" id="outer_3"><div class="inner" id="inner_3"><input type="image" src="3.jpg"></div></div>
</div>
I have tried the below solution I found here but couldn't help. I am totally new in programming, may I know how can I do this?
var $images = $('.inner input');
var loaded_images_count = 0;
$images.load(function(){
loaded_images_count++;
if (loaded_images_count == $images.length) {
$('.container').show();
}
});
Your code is almost correct. The issue you have is that you're using the load() method, which is used to retrieve content from the server using AJAX, not the load event, which fires on img elements when they are ready to be displayed.
To fix this use on() instead of load():
var $images = $('.inner input');
var loaded_images_count = 0;
$images.on('load', function() {
loaded_images_count++;
if (loaded_images_count == $images.length) {
$('.container').show();
}
});
Normally, loaded doesn't mean rendered.
If you develop application on framework such as Angular, It will provided rendered event for you.
In case you develop application by only pure javaScript or even with jQuery,
Use setTimeOut might be help you (just in some case).
$images.load(function(){
loaded_images_count++;
if (loaded_images_count == $images.length) {
setTimeout(function(){
$('.container').show();
}, 0);
}
});
I am wondering whether there is any way to overcome the new autoplay policy by Google.
I want to play a short sound snippet when a link is hovered, which unfortunately just works in Firefox and not in Chrome and Safari anymore.
Is there any way to find a work around for that problem?
Probably not I guess, just thought to address this question to more educated people in that field. Maybe someone has an idea.
That's the Code which works in Firefox and used to work in Chrome and Safari as well - but not anymore.
html
<span class="hit hitme">Just hit me up!</span>
<audio id="HitMe">
<source src="sound/hitmeup.mp3">
</audio>
jQuery
var audio = $("#HitMe")[0];
$(".hitme").mouseenter(function() {
audio.play()
$(".hitme").mouseleave(function() {
audio.pause();
});
});
Your question is short but there are actually many things to be said.
First off, it's always nice to use VanillaJSā¢ instead of jQuery when it comes to policy changes, because standards get immediatly propagated to plain JavaScript, whereas it takes a while for the change to propagate up to third-party libs like jQuery. The nice thing with plain JavaScript is that you can create an audio object with new Audio(<source>) - no need for any HTML element! See below for an example:
const audio = new Audio("https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3");
// wait for the DOM to load
window.onload = () => {
// play audio on click
const clickToPlay = document.querySelector('#click-to-play');
clickToPlay.onclick = () => audio.play();
// play/pause audio on hover
const hoverToPlay = document.querySelector('#hover-to-play');
hoverToPlay.onmouseover = () => audio.play();
hoverToPlay.onmouseout = () => audio.pause();
}
/* just some styling, not useful for the solution */
#click-to-play {
padding: 1em;
background-color: steelblue;
}
#click-to-play:hover {
cursor: pointer;
}
#hover-to-play {
padding: 1em;
background-color: lightblue;
}
#hover-to-play:hover {
cursor: crosshair;
}
<div id="click-to-play">
Click to play
</div>
<div id="hover-to-play">
Hover in to play, hover out to pause
</div>
Great! Except, as you precised, the autoplay on hover that might be blocked by the 2017 update on autoplay in Chrome.
But it's not necessarily a bad thing. This update was made to make the web user experience better. If you're trying to find hacks on how to bypass it, you're doing it wrong ;) The update states that autoplay with sound is allowed if the user has interacted (eg with a click). Therefore, when designing your website, make sure the user clicks somewhere on your page before the autoplay appears. Here's an example with a two-steps click to authorize, hover to play user experience:
const audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
window.onload = () => {
const clickToAuthorize = document.querySelector('#click-to-authorize');
const hoverToPlay = document.querySelector('#hover-to-play');
clickToAuthorize.onclick = () => {
hoverToPlay.style.display = 'block';
}
hoverToPlay.onmouseover = () => audio.play();
hoverToPlay.onmouseout = () => audio.pause();
}
#click-to-authorize {
padding: 1em;
background-color: steelblue;
}
#click-to-authorize:hover {
cursor: pointer;
}
#hover-to-play {
padding: 1em;
background-color: lightblue;
display: none;
}
#hover-to-play:hover {
cursor: crosshair;
}
<div id="click-to-authorize">
Click if you want to hear a T-Rex roar!
</div>
<div id="hover-to-play">
Hover to play/pause
</div>
I'm quite new in coding, trying to educate myself because i'm interested. So, sorry if it's going to be a bit dumb question or not so specific or not really correct...
On my "practicing site" i'm having some navigation links, which are referring to different innerHTML contents (like different pages). I used the 'onClick' event to make them show up, for example like this:
<div class="nav" onClick="changeNavigation('a')">menu</div>
It works with texts perfectly, but my problem is that i don't know how to make the same with an image. So when i click on the image, i want to be redirected to that innerHTML page, like i did it with the text based button. I tried to do it like these two ways, but none of them worked.
<img src="picture.png" onClick="changeNavigation('a')" />
<div onClick="changeNavigation('a')"><img src="picture.png"></div>
Is it possible to make this with an image and the 'onClick' event? Or how else can i make this work?
By the way this is my script to make innerHTML show up:
<script>
function changeNavigation(id) {
document.getElementById('main').innerHTML = document.getElementById(id).innerHTML
}
</script>
I also tried to add my image an id that says 'main' like in the script this way, but with no result.
<img id="main" onClick="changeNavigation('f')" src="picture.png" />
Can you help me please? I would appreciate any answer, because i already searched about this and i didn't find anything that could've helped solve my problem and i'm really stuck right now.
(Sorry if my english isn't the best, it's not my native language.)
I have updated my answer to what you want. You need to the divs id you want to display as a parameter to the function you use for onclick. A sample is below.
var divs = ["Menu1", "Menu2", "Menu3", "Menu4"];
var visibleDivId = null;
function toggleVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.main_div{text-align:center; background: #00C492; padding:20px; width: 400px;}
.inner_div{background: #fff; margin-top:20px; height: 100px;}
.buttons a{font-size: 16px;}
.buttons a:hover{cursor:pointer; font-size: 16px;}
img {cursor:pointer}
<div class="main_div">
<div class="buttons">
<img src="http://www.clker.com/cliparts/J/g/2/D/p/I/one-hi.png" width="50px" onclick="toggleVisibility('Menu1');"> <img src="http://www.clker.com/cliparts/E/x/J/x/m/z/blue-number-two-hi.png" width="50px" onclick="toggleVisibility('Menu2');">
<img src="http://www.clker.com/cliparts/L/H/T/b/g/N/three-md.png" width="50px" onclick="toggleVisibility('Menu3');">
<img src="http://www.clker.com/cliparts/v/G/G/A/D/s/four-md.png" width="50px" onclick="toggleVisibility('Menu4');">
</div>
<div class="inner_div">
<div id="Menu1">I'm container one</div>
<div id="Menu2" style="display: none;">I'm container two</div>
<div id="Menu3" style="display: none;">I'm container three</div>
<div id="Menu4" style="display: none;">I'm container four</div>
</div>
</div>
You can just keep all of the sections as children of #main, and selectively show them when the section button in clicked. E.g.,
HTML
<nav>
<button type="button" data-index=0>Show one</button>
<button type="button" data-index=1>Show two</button>
<button type="button" data-index=2>Show three</button>
</nav>
<main id="main">
<section>One</section>
<section class="hidden">Two</section>
<section class="hidden">Three</section>
</main>
CSS
.hidden {
display: none;
}
JavaScript
const buttons = Array.from(document.querySelectorAll('button'));
const contentBlocks = Array.from(document.querySelectorAll('section'));
function hideSections (arr) {
arr.forEach(a => {
a.classList.add('hidden');
});
}
function showSection (index, sections) {
// Just a basic check, not exhaustive by any stretch
if (index !== undefined && sections !== undefined) {
hideSections(sections);
sections[index].classList.remove('hidden');
}
}
buttons.forEach(button => {
button.addEventListener('click', () => {
const contentBlocks = Array.from(document.querySelectorAll('section'));
const index = button.getAttribute('data-index');
showSection(index, contentBlocks);
});
});
Obviously you'll have to adjust your selectors for your use case, but Here's a pen
Here's a GitHub Gist pointing to some examples I created on JSFiddle based off of your specific use case (Stack Overflow doesn't let me post links to JSFiddle directly without including code here, but it's easier to follow along/experiment entirely in JSFiddle):
https://gist.github.com/andresn/f100386f06ee28e35bd83c62d9219890
More advanced stuff:
Ideally, you'd use what's called event delegation instead of adding an onclick to every anchor (DRY = Don't Repeat Yourself is good to always keep in mind while programming and so is KISS = Keep It Simple Silly). Here is a resource explaining event delegation:
https://davidwalsh.name/event-delegate
You can even take this further by preloading all your images so they load behind the scenes when the user first loads the page:
https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
i'm back from nowhere.
I have something for school where we need to make a website.
Everyone in my class uses those easy drag 'n drop builders.
I'm ofcourse making it with Notepad++.
So, a 1990 looking page is ofcourse not enough with some fun music.
I have found around 3 to 4 Mario Bros online music to use.
But it only starts the first source link, never the others.
I want to know how to do it, Google doesn't really help.
This is my code:
<audio autoplay="autoplay" controls="controls" title="Radio implented by Rootel">
So my question is, how do I autoplay this list? I didn't give a full list of the music, sorry.
Here you can make it with javascript!
//javascript
var _player = document.getElementById("player"),
_playlist = document.getElementById("playlist"),
_stop = document.getElementById("stop");
// functions
function playlistItemClick(clickedElement) {
var selected = _playlist.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
}
clickedElement.classList.add("selected");
_player.src = clickedElement.getAttribute("data-ogg");
_player.play();
}
function playNext() {
var selected = _playlist.querySelector("li.selected");
if (selected && selected.nextSibling) {
playlistItemClick(selected.nextSibling);
}
}
// event listeners
_stop.addEventListener("click", function () {
_player.pause();
});
_player.addEventListener("ended", playNext);
_playlist.addEventListener("click", function (e) {
if (e.target && e.target.nodeName === "LI") {
playlistItemClick(e.target);
}
});
.selected {
font-weight: bold;
font-size:20px;
}
<!--html-->
<audio id="player"></audio>
<ul id="playlist"><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%201%20by%20Lionel%20Allorge.ogg">Space 1</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%202%20by%20Lionel%20Allorge.ogg">Space 2</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%203%20by%20Lionel%20Allorge.ogg">Space Lab</li></ul>
<button id="stop">Stop</button>
hope it helps!!!
I've found some Javascript code on the web for toggling between two images when clicking on them as in this example.
Now I wonder how to achieve the same result using divs with the pictures being inside the divs.
Both the small and the large image will each be the background image of a div which is inside another div that forms the border (I need to do this to be able to set the inner border radius of the image, which I can when I use an inner div and set its border radius). So I have:
<div class="bordersmallpicture"><div class="smallpicture"></div></div>
and
<div class="borderlargepicture"><div class="largepicture"></div></div>
How can I tell Javascript to toggle between those two div couples instead of images? Here is the Javascript code that I found for the images:
<script>
var imageURL = "small-picture.png";
if (document.images) {
var smallpicture = new Image();
smallpicture.src = "small-picture.png";
var largepicture = new Image();
largepicture.src = "large-picture.png";
}
function changeImage() {
if (document.images) {
if (imageURL == "large-picture.png") {imageURL = "small-picture.png";}
else {imageURL = "large-picture.png";}
document.myimage.src = imageURL;
}
}
</script>
And the HTML part:
<img src="small-picture.png" name="myimage" title="Click to resize" alt="tree">
Can anyone give me a hint how to edit this code to toggle between the div couples mentioned above? Or will a whole new code be necessary when dealing with divs?
You simply need to toggle the classes. See a running example using your images as CSS background in the classes:
<div id="border-div" class="bordersmallpicture">
<div id="image-div" class="smallpicture"></div>
</div>
The the Javascript becomes:
<script>
function changeImage() {
var currentClass = document.getElementById('border-div').className;
if(currentClass == 'borderlargepicture') {
document.getElementById('border-div').className = 'bordersmallpicture';
document.getElementById('image-div').className = 'smallpicture';
} else {
document.getElementById('border-div').className = 'borderlargepicture';
document.getElementById('image-div').className = 'largepicture';
}
}
</script>
If you expect using javascript a lot, I recommend using jQuery which would make the code easier:
<script>
function changeImage() {
$('#border-div').toggleClass('bordersmallpicture').toggleClass('borderlargepicture');
$('#image-div').toggleClass('smallpicture').toggleClass('largepicture');
}
</script>
toggleClass turns ON/OFF a class (Here is the example)