Jquery Code Sinppets to Solve - javascript

Can anybody tell me what are the possible solutions for these??
Question 1: A web page as a form with the id "my_form" and a few elements with the class "excluded" applied. How can you make a copy of the form and get rid of all elements with the excluded class, only from the new copy of the form?
Question 2: Examine this code snippet. What do you think it's supposed to do? Why doesn't it work? How would you fix it?
$("li").each(function () {
if ($(this).find("ul")) {
$(this).css("background-color", "gray");
} else {
$(this).css("background-color", "white");
}
});
Question 3: A user is complaining that audio is playing even after hitting the play/pause button. Given the below implementation, why would that happen? How would you fix it?
// Pause Button Implementation:
$("#togglePlayPause").on("click", function () {
if (audio.paused === true) {
audio.play();
} else {
audio.pause();
}
});
// when the current audio has played all the way through, read the next element.
audio.addEventListener("ended", function () {
if (audio.paused === false) {
var nextElement = _getNextElement();
// scroll the page so that the next element we're reading is at the top of the browser window.
$(window).animate(scrollTop: nextElement.offset().top, 400, function () {
_playElementAudio(nextElement);
});
}
});
Any help will be appreciated..

Question 1
$("#form").not(".excluded").clone().appendTo("#anotherForm");

Related

Move color of an HTML element to another page

Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}

HTML buttons will only work only on webpage re/-load

EDIT : Thanks to everyone who tried to help me. I appreciate the tips guys.
I changed my window.onloadand inserted the two event listeners inside of it.
After that I took the idea of #Ito Pizarro , and implemented it in my own way.
The result looks like this :
function openDoor() {
var x_1 = document.getElementById('img1');
var x_2 = document.getElementById('img2');
is_visible = (x_1.style.visibility == "hidden");
if (is_visible) {
x_1.style.visibility = "visible";
}
else {
x_2.style.visibility = "hidden";
}}
And I also did the same for my closeDoor() function.
END OF EDIT
I create a HTML page, with two buttons. Every button has its purpose when it's being clicked. The first one will show an image of an opened door. The second button will show an image of a close door. When the page is loaded no image is being shown. They appear only if their button is clicked.
Tried to created a nested if-statement with the a global bool that will make it run infinitely.
Also tried a for & while loop.
But I am new to programming and I struggle a bit.
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
}
window.onload = function () {
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
function openDoor(){
document.getElementById('img1').style.visibility = "visible";
}
function closeDoor(){
document.getElementById('img2').style.visibility = "visible";
}
In the code exist two problems :
I load the page and click the "close door" button and the closed door image appears. If I decide to open the door again by pressing the "open door" button, it wont do it.
I load the page and click the "open door" button first. The open door image appears and the if I click on the "close door" button and the image also appears, but I cant repeat the process by re-clicking the "open door" to reopen it.
You are assining a function on the onload event twice. By doing this the first delaration will never be triggered.
It should be more something like :
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
Don't forget to validate the answer if you have what you were looking for
EDIT: In addition to lucien-dulac's point about window.onload…
It looks like your two event handlers do a single thing to either of two separate elements.
openDoor() will only ever make #img1 visible.
closeDoor() will only ever make #img2 visible.
If you want subsequent clicks on #OpenDoor or #CloseDoor to change the visibility style of their respective target elements — #OpenDoor controls #img1, #CloseDoor controls #img2 — you would need to write a toggle into openDoor() and closeDoor().
Something like…
function openDoor(){
var el = document.getElementById('img1'),
is_visible = ( el.style.visibility === "visible" );
if ( is_visible ) {
el.style.visibility = "hidden";
} else {
el.style.visibility = "visible";
}
}

hide certain content based of an event [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I cannot find the right solution how hide a certain content on new part of page generated from PHP. (I am new in javascript)
I have a page, which loads new content below the actual, if a visitor scrolling down (like on Facebook.)
Each time, when a new content will displayed, I want run a function, which will hide certain content on the page.
Here is the code which loads new content. This works great.
(function() {
var $loadMore = $('.load-more').first();
if (!$loadMore.get(0)) {
return;
}
var timeout;
var $loadMoreLink = $loadMore.children('a'),
$list = $loadMore.prev('ul');
$loadMoreLink.on('click', function(event) {
event.preventDefault();
getMore();
});
function checkForMore() {
if (($window.scrollTop() + $window.height()) > ($list.offset().top + $list.height())) {
getMore();
}
}
function getMore() {
if (!$loadMoreLink.is(':visible')) {
return;
}
$loadMoreLink.attr('hidden', true);
$.get($loadMoreLink.attr('href'), function(response) {
$list.append(response);
var moreUrl = $list.children().last().data('more-url');
if (moreUrl) {
$loadMoreLink.attr('href', moreUrl);
$loadMoreLink.removeAttr('hidden');
}
else {
$loadMore.attr('hidden', true);
}
console.log(moreUrl)
});
}
$window.on('scroll', function() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(checkForMore, 50);
});
checkForMore();
})();
Here is my code, with help of which I want to hide certain content. That does not work :(. I have tried really much, and spent many days on that.
var hideUnity = document.getElementsByClassName("load-more");
for (var i = 0; i < hideUnity.length, i++) {
hideUnity[i].addEventListener("click", function() {
if (something && something) {
$(document).ready(function(){
$("li.unity").hide();
});
}
});
}
Link to loading file at page
<div class="load-more">
Load more
</div>
Can someone help me, please? :). Thanks.
I don't know if there is a reason to mix native js and jQuery, but you can do your function easily using the framework:
$(function(){
$(".load-more").on('click', function(){
// now $(this) represents clicked object while $('.load-more') still represents all elements with provided class
if( whateveryouwant ){
$("li.unity").hide();
}
});
});
Edit
If you need to use a delegated event, just replace
$(".load-more").on('click', function(){....
by
$(document).on('click', '.load-more', function(){....

Catching all audio end events from dynamic content in jquery

I have seen similar questions - but not that fix my problem!
I have audio on my page and when one ends, I want the next to start, but I can't even get the ended to trigger...
I cut the code down to this:
function DaisyChainAudio() {
$().on('ended', 'audio','' ,function () {
alert('done');
});
}
This is called from my page/code (and is executed, setting a break point shows that).
As far as I understand this should set the handler at the document level, so any 'ended' events from any 'audio' tag (even if added dynamically) should be trapped and show me that alert...
But it never fires.
edit
With some borrowing from Çağatay Gürtürk's suggestion so far have this...
function DaisyChainAudio() {
$(function () {
$('audio').on('ended', function (e) {
$(e.target).load();
var next = $(e.target).nextAll('audio');
if (!next.length) next = $(e.target).parent().nextAll().find('audio');
if (!next.length) next = $(e.target).parent().parent().nextAll().find('audio');
if (next.length) $(next[0]).trigger('play');
});
});
}
I'd still like to set this at the document level so I don't need to worry about adding it when dynamic elements are added...
The reason it does not fire is, media events( those specifically belonging to audio or video like play, pause, timeupdate, etc) do not get bubbled. you can find the explanation for that in the answer to this question.
So using their solution, I captured the ended event, and this would allow setting triggers for dynamically added audio elements.
$.createEventCapturing(['ended']); // add all the triggers for which you like to catch.
$('body').on('ended', 'audio', onEnded); // now this would work.
JSFiddle demo
the code for event capturing( taken from the other SO answer):
$.createEventCapturing = (function () {
var special = $.event.special;
return function (names) {
if (!document.addEventListener) {
return;
}
if (typeof names == 'string') {
names = [names];
}
$.each(names, function (i, name) {
var handler = function (e) {
e = $.event.fix(e);
return $.event.dispatch.call(this, e);
};
special[name] = special[name] || {};
if (special[name].setup || special[name].teardown) {
return;
}
$.extend(special[name], {
setup: function () {
this.addEventListener(name, handler, true);
},
teardown: function () {
this.removeEventListener(name, handler, true);
}
});
});
};
})();
Try this:
$('audio').on('ended', function (e) {
alert('done');
var endedTag=e.target; //this gives the ended audio, so you can find the next one and play it.
});
Note that when you create a new audio dynamically, you should assign the events. A quick and dirty solution would be:
function bindEvents(){
$('audio').off('ended').on('ended', function (e) {
alert('done');
var endedTag=e.target; //this gives the ended audio, so you can find the next one and play it.
});
}
and run bindEvents whenever you create/delete an audio element.

How can one <img> tag be used to execute 2 different js functions?

How can I set up one image, that when clicked changes to another image and then when clicked again reverts back to the original image while still carrying out functions independently. In my example I want a Play button that when pressed turns to a pause button. However I need to have both play and pause functionalities when the correct button is pressed. These work on do different buttons but I would like the one button to have all the functionality. I have tried a few things but everytime, one of the play/pause functions are not letting the other work.
$('#startSlider').click(function (){
if (document.getElementById("startSlider").src = "Play.png"){
document.getElementById("startSlider").src = "Pause.png";
scrollSlider();
}
else if (document.getElementById("startSlider").src != "Play.png"){
clearTimeout(tmOt);
document.getElementById("startSlider").src = "Play.png";
}
});
<img src="Play.png" id="startSlider"/>
problem is in your if block,
you are using = not ==
if (document.getElementById("startSlider").src = "Play.png"){// you are assigning here not comparing
you are assigning play.png every times when the click calls on the image.
you are using jquery then why are you not using this to make it more simple.
$('#startSlider').click(function (){
if (this.src == "play.png"){
this.src = "pause.png";
}else{
this.src = "play.png";
}
});
check this fiddle
I like using classes in these situations as it makes the code a little easier to follow:
$('#startSlider').click(function (){
$(this).toggleClass('pause')
if ( $(this).hasClass('pause') ) {
// Button is paused change to play
$(this).attr('src', 'Play.png')
// Pause function goes here
} else {
// Button is play change to pause
$(this).attr('src', 'Pause.png')
//play function goes here
}
})
You can do this with a little state machine. You keep the states inside an object, and handle the next state in the event listener of the button:
var states = {
_next: 'play',
next: function() {
return this[this._next]()
},
play: function() {
img.src = 'pause.jpg'
button.textContent = 'Pause'
this._next = 'pause'
},
pause: function() {
img.src = 'play.jpg'
button.textContent = 'Play'
this._next = 'play'
}
}
button.addEventListener('click', states.next.bind(states))
This is more of a general answer to your problem, that you'd have to adapt to your code.
DEMO: http://jsbin.com/moxoca/1/edit *
* The images might take a second to load.

Categories

Resources