I have this js
code
var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');
parent.addEventListener('mouseenter', function(){
child.style.opacity = shown ? 0 : 1;
shown = !shown;
});
The js
is related to the following css
* {
margin: 0;
padding: 0;
}
.parent {
width: 100%;
margin: 10px auto;
position: relative;
}
.child {
position: absolute;
top: 0;
width: 100%;
height: 100%;
display: block;
overflow: hidden;
transition: opacity 0.5s linear;
}
p {
padding: 1em;
}
and html
:
<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />
<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>
The problem is that I use this code for a particular page, not for the entire site and it works just fine except the fact that on any other page (Home, etc) I receive an error telling me that the .parent
element is missing. Nothing unusual as long as I don't need it in that page at all.
Uncaught TypeError: Cannot read property 'addEventListener' of null(anonymous function) @ shomz.js:6
If this helps, in this moment, the js
code defined as shomz.js
is registered like this:
...
// Main Scripts
function register_js() {
if (!is_admin()) {
$url_prefix = is_ssl() ? 'https:' : 'http:';
// Register
wp_register_script('shomz', THB_THEME_ROOT . '/assets/js/plugins/shomz.js', 'jquery', null, TRUE);
// Enqueue
wp_enqueue_script('shomz');
wp_localize_script( 'app', 'themeajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
}
...
At this point, in order to avoid defining .parent/.child
elements for every single page, I was wondering, is there any possibility to register the js
in the script-calls.php
file, being active only for a defined page(s) by id for example?