.click doesn't work properly on jquery - javascript

PHPstorm spoiled my files just now, so I have to rework everything. And for some reason I can't get this working - click event just don't happen at all, neither with $("body"). It does work with $(document).on(...) though.
(script is inside head and script tags)
$("#cover").on('click',function(e) {
$(e.target).removeClass("no");
$(e.target).addClass("yes");
});
<body>
<div id="button"></div>
<div id="cover">
<div class="rows" id="row1"></div>
<div class="rows" id="row2"></div>
<div class="rows" id="row3"></div>
<div class="rows" id="row4"></div>
<div class="rows" id="row5"></div>
<div class="rows" id="row6"></div>
</div>
</body>

Code is executed in the order in which it's found on the page. So this:
$("#cover")
Needs to be executed after this is added to the page:
<div id="cover">
Otherwise that element won't be found by that selector, because it doesn't exist yet.
One approach is to move the JavaScript code to the bottom of the page. (Or at least to after the target element exists.) Another is to wrap it in the jQuery function which will attach it to the document's ready event:
$(function () {
// add your code here
// this will execute after the DOM is completely loaded
});

Try doing this. It will execute once your DOM is ready.
$(function(){
$("#cover").on('click',function(e) {
$(e.target).removeClass("no");
$(e.target).addClass("yes");
});
});

You could try reverting your changes in PHPStorm by right-clicking the folder, navigating to Local History -> Show History -> right click file(s)/folder(s) and select Revert Changes.
If that doesn't work do the following:
Move your javascript to the bottom of the page
Wrap the click with $(document).ready(...)
For debugging purposes do console.log($("#cover")); as your first line before binding a click event to see if jQuery object length is 1 or 0. If 1 the element is matched and found, if 0 then element doesn't exist or no match found.

Related

Jquery .load() only parent and ignore children

So, I am trying to load picture from another page using Jquery .load(), now the element I am trying to load has multiple children element which also load on current page, now obviously I could hide those divs but first I want to know if there's way to only grab parent div and leave out children.
I have tried using parent() method but since .load() works differently, it didn't work as intended. (Unless I missed something)
$('#myNewDiv').load('/robots .heading-image');
Here's HTML code from the other page
<div class="heading-image" style="background-image:url(imagelinkhere.png)">
<div class="heading-image_cover">
<div class="left">
<div class="heading-image title">Heading Title</div>
<div class="heading-image desc">I am a desc</div>
</div>
<div class="right">
<div class="heading-image stat">Stat text</div>
</div>
</div>
</div>
That's the code I am using right now, but .heading-image has multiple child elements as mentioned above.
To sum up, I need to load only parent element and ignore all child elements of the div mentioned above without having to load those children on current page and hide them (If possible)
From what I understand, your goal seems to be to copy the empty div to a new page, while maintaining the background image associated with the <div> tag.
The simplest approach would be to add to a stylesheet in which both of the pages can reach. For example:
CSS
.heading-image{
background-image:url(imagelinkhere.png);
}
JavaScript
$('#myNewDiv').html("<div class="heading-image"></div>");
Then in the head of both HTML documents, have <link rel="stylesheet" href="style.css"> to point towards the correct stylesheet for both pages.
If you just want the empty <div class="heading-image"></div> you could use the load() complete callback to empty it:
$('#myNewDiv').load('/robots .heading-image', function(){
// new html exists in page now, 'this' is #myNewDiv element
$(this).find('.heading-image').empty();
});
If there are resources inside that element like images, videos etc that you don't want to load in page you could also parse the :
$.get('/robots').then(function(html){
var $hImage = $(html).find('.heading-image').empty();
$('#myNewDiv').html($hImage)
});
With all that said I don't see why you need to extract an empty element from another page and can't just do:
$('#myNewDiv').html('<div class="heading-image"></div>')

Display a loading animation until a <div> appears?

I'm running an asynchronous 3rd party script that loads an image gallery into my page, but unfortunately their code doesn't provide me with a callback after their image gallery has finished loading.
The modal starts off like this:
<div class="modal-body">
<div class="container-fluid" id="cincopa">
</div>
</div>
After the gallery is loaded, the modal looks like this:
<div class="modal-body">
<div class="container-fluid" id="cincopa">
<div id="ze_galleria">
//gallery stuff
</div>
</div>
</div>
So I need some way to display a loading animation until #ze_galleria appears. The loading animation function I can do myself, but is there something in jQuery that will listen for when a certain DOM element is created? Once the DOM element appears, it'll run the callback to remove the animation.
Based on how that script adds the gallery/gallery items you could use the DOMSubtreeModified event and then check if that particular item were added
document.addEventListener("DOMSubtreeModified", function(e) {
if (document.querySelector("#ze_galleria")) {
// exists
}
});
Here is a DOM tree event list, where you can check other possible events that might could be used.
https://developer.mozilla.org/en-US/docs/Web/Events
Update
Make sure you take a look at the MutationObserver as well, as it has very good browser support nowadays.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Also, you can set an interval:
var cincopa = $('#cincopa');
var counter = 0;
var intervalCode = setInterval(function(){
if (cincopa.find('#ze_galleria').length){
clearInterval(intervalCode);
yourCallback();
}
counter++;
console.log(counter + ' seconds past till the event loaded.');
}, 1000);
I think the code is intuitive, but if there is any doubt, just ask :)
Presuming that your "3rd party library" is going to totally overwrite the contents of what ever you point it at (as your example code suggests it does). You can solve your problem simply by adding an img:
<div class="modal-body">
<div class="container-fluid" id="cincopa">
<img src="loading.gif"/>
</div>
</div>
When the library has done what it needs to do it will overwrite the contents of the div <div class="container-fluid" id="cincopa"> resulting in:
<div class="modal-body">
<div class="container-fluid" id="cincopa">
<div id="ze_galleria">
//gallery stuff
</div>
</div>
</div>
thus removing your loading image.

Get the innerhtml of element which is loading at run time

This is div which loads elements at rum time.
<div class="name" id="projct_name"></div>
after loading elements its becomes:-
<div id="projct_name" class="name">
<div>
<span >Proof testers</span>
</div>
</div>
I want the value of span.
$(document).ready(function() {
var prodct_name=$('#projct_name').find('div').find('span').html();
alert(prodct_name);
});
Each time page load get the alert null value because elements loads after alert.
I want to delay my js code so that all elements of page loads before my code run. It can be possible??
Try the below code:-
function pageLoadCompelet(){
var prodct_name=$('#projct_name').find('div').find('span').html();
alert(prodct_name);
}
And call this function on window.onload :-
window.onload=pageLoadCompelet;
I think Jquery Initialize will solve your issue.
Step 1: Insert this in the head-section of your page:
<script src="https://raw.githubusercontent.com/AdamPietrasiak/jquery.initialize/master/jquery.initialize.js"></script>
Step 2: Place the following javascript below or above the other code you already tried:
$("#projct_name span").initialize( function(){
alert($(this).html());
});
The plugin uses MutationObserver which is a really robust way of handling DOM changes.

JQueryMobile: When data-role="page" 's JS generated content is created/remove?

Given a one-html-multiple-pages app, in each of my pages I plan JS inject long html codes and animations which can be heavy. HTML code such :
<div data-role="page" id="page11">
...
</div>
<div data-role="page" id="page12">
<h2 id="anchor12">Title: Page 12</h2>
<script>myScript12() // inject complex content to #anchor12</script>
</div>
1. When does my myScript12() is fired ? (When I open the .html file or when I click and open the #page12 ?
2. What happen to the JS generated content when I leave #page12 for an other page ?
Edit: I don't want to load all my 20 heavy pages on .html load.
Solution: +1 for the detailed explanation by Gajotres (JQM: document ready vs page events), below is my current solution. To run the js ONLY when the given data-role="page" is displayed...
Use the following JQM HTML/JS:
<div data-role="page" id="page12">
<h2 id="anchor12">Title: Page 12</h2>
<script>
$('#page12').on('pageinit') { //only run when page is displayed
myScript12() // inject complex content to #anchor12
});</script>
</div>
That script will execute as soon as page is loaded into the DOM. That's why page events exist. Basically if you want to time your code execution do it inside a page event. If you want to find more about page event's read my other answer: jQuery Mobile: document ready vs page events.
When you leave your page that content is still there loaded into the DOM. If you want to prevent large DOM content you can use pagehide event to clean previous page content. There's also an attribute that can be placed inside a data-role="page" div to prevent DOM cashing. Attribute name is data-dom-cache="true" and you can find more abut it here.

calling an external script and .load jquery conflict

I'm pretty sure this is another DOH! facepalm questions but as designer and not a programmer I need some help getting it right.
What I have is an index file calling local .html files via jQuery .load. Just like this:
(some tabs functionality not relative here - thus the link target call)
Lightbox</li>
<div id=lightbox">
<div class="load">
<script type="text/javascript">
$('.load').load('examples/lightbox.html');
</script>
</div>
</div>
I also have an external .js file that has a bunch of functions that handles some lightboxes among other things. Standard <script src="js/typography.js" type="text/javascript"></script>
Which contains:
$(document).ready(function(){
$(".open-lightbox").on("click", function(){
$('.lightbox').css('display','block');
});
$('.close-lightbox').click(function(){
$('.lightbox').css('display','none');
});
});
My problem is that if the externally called .html file has any elements dependent on the .js file ie. the lightbox popup it doesn't work.
something like :
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
If i move the html code right to the index page instead of the .load, no problem, same if I moved the JS as an inline <script>...</script> rather than calling it extrenally. Works fine in both cases.
My spidey sense tells me this has something to do with my function and .load not executing in the order I need them to, but my javascript copy/paste skills only go this far.
Can anyone tell me if I can make this combination work? I'd really appreciate it.
EDIT
Maybe I explained my self poorly so let me try and post a better example.
If my index code is as followed everything works: My lightbox pops up as intended.
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
</div>
<--End Tab Content-->
</div>
When the said tab is clicked the content inside "thistabid" show up. Whatever that content may be.
Now if i do :
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
<script type="text/javascript">
$('.somehtmlpage-load').load('examples/lightbox.html');
</script>
</div>
<--End Tab Content-->
</div>
The lightbox doesn't work. The content of lightbox.html is
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
Same as the html in the 1st example where everything works. The only difference it's being jQuery loaded rather than hard coded.
What I mean by "if the externally called .html file has any elements dependent on the .js file ie. the lightbox popup" is that if the html is part of the externally called file then the lightbox function isn't working. If it's hard coded it pops up like intended.
On 1st glance the .on seems like should be the solution but most likley my implementation of it is off the mark :/
The 'on' or the 'live' function needs to be applied through an element that exists on the page. Generally some parent of the actual element is used. Can you try something on the following lines with the correct references to the elements on your page:
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
<!--leave tab empty for now -->
</div>
<--End Tab Content-->
</div>
<script>
(function(){
$('.somehtmlpage-load').load('examples/lightbox.html');
//live or on needs to be applied to an element that exists on th page
$('#thistabid').on('click', '.open-lightbox', function(){
$('.lightbox').css('display','block');
});
$('#thistabid').on('click', '.close-lightbox', function(){
$('.lightbox').css('display','none');
});
})();
</script>
There seems to be a race condition between your load() and document ready.
To address this you'll need to:
either wait for the load() to complete before you attach the click events
or attach the click to the container of your load() step and use event delegation.
See this page and this other one for more information on how to use on() for delegation.
The code would look like this:
$(".somehtmlpage-load").on("click", ".open-lightbox", function(){
$('.lightbox').css('display','block');
});
Using a SSI solved my problem. I was trying to keep it all Local Drive friendly but it seemed to be causing more problems than anticipated.
Pick your favorite dev environment...I didn't run into any conflicts on either.
ASP - <!--#include file = "examples/lightbox.html" -->
PHP - <?php include 'examples/lightbox.html';?>
Just in case someone else runs into a similar problem.

Categories

Resources