Javascript error: element is null - javascript

Here is all of my code... The inline JavaScript alert is firing off nicely, but the external alert is not. Whenever I reload the page I get a console error log saying "TypeError: tileBlock is null".. Any ideas? I've yet to come across this issue and I'd rather not be forced into writing all of my Javascript event handlers inline. Thanks!
#tileBlock {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #0b0b0b;
background-position: center;
background-repeat: no-repeat;
background-image: url(photo.jpg);
border: 20px solid #fff;
background-size: cover;
}
#media (max-width: 400px) {
#tileBlock {
border-width: 8px;
}
}
<body>
<div class="wrapper" id="tileBlock" onclick="alert('You clicked (inline)')"></div>
</body>
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
alert('you clicked(external script)');
}

Include jquery library and try this:
$('#tileBlock').onclick(function(){
alert('you clicked(external script)');
});
Also I have tried your code and it works.(not my jquery)
Try this: http://jsfiddle.net/XcsN/evK3v/

I just needed a window.onload... Thanks everyone for the help!
window.onload=function(){
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
alert('you clicked yes');
}
};

No need window before since it's reserved
onload=()=>{
let elem // etc..
elem.onclick=()=> // stuff ..
}
fiddle

Related

Initiating jQuery script works when placed in console but not when placed into site code

I have some code that will simply open a box copying in the image that is clicked.
I don't so much need help with the code, and you don't need to know anything about the layout or creation of the image box. Just have faith this code works.
I have a couple functions:
var caseStudySlider = $('.case-study-slider-image');
var productImageZoom = $('.photo');
if (caseStudySlider.length) {
caseStudySlider.click(function () {
var bg = $(this).css('background-image');
bg = bg.replace('url(', '').replace(')', '').replace(/\"/gi, "");
var targetZoomer = $('#image-zoomer');
targetZoomer.attr("src", bg);
var zoomedImage = $('#image-zoom-contain');
if (zoomedImage.hasClass('open')) {} else {
zoomedImage.addClass('open');
}
});
}
if (productImageZoom.length) {
productImageZoom.click(function () {
var bg = $(this).css('background-image');
bg = bg.replace('url("', '').replace('")', '').replace(/\"/gi, "");
var targetZoomer = $('#image-zoomer');
targetZoomer.attr("src", bg);
var zoomedImage = $('#image-zoom-contain');
if (zoomedImage.hasClass('open')) {} else {
zoomedImage.addClass('open');
}
});
}
if (productImageZoom.length || caseStudySlider.length) {
$('.close-zoomed-image').click(function () {
var zoomedImage = $('#image-zoom-contain');
if (zoomedImage.hasClass('open')) {
zoomedImage.removeClass('open');
} else {}
});
}
These are placed inside a script tag and ran from the footer of a WordPress site. For this I use a 'header & footer scripts' plug-in to place the snippets of script into the footer.
There are two uses of the script, one is on a blog style page, one is on product pages. The two triggers are the two variables defined at the top of my code:
var caseStudySlider = $('.case-study-slider-image');
var productImageZoom = $('.photo');
The code works for one of the pages caseStudySlider. But, doesn't work for the product pages. However if I copy and paste the code into the console, it works on both pages!
How can I identify / highlight reasons this may be the case?
Additional code that is relevant but not necessary to answer the question I don't think:
Include of box to populate:
<div id="image-zoom-contain" class="">
<div class="image-zoom-inner">
<img src="" id="image-zoomer" class="image-zoomer" alt="zoomed image">
</div>
</div>
CSS:
/* ZOOMABLE IMAGE */
.case-study-slider-image,
.photo {
cursor: zoom-in;
}
#image-zoom-contain {
width: 100%;
height: 100%;
display: none;
position: fixed;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.7);
z-index: 1000000;
}
#image-zoom-contain.open {
display: block!important;
}
.image-zoom-inner {
width: auto;
height: calc(100% - 80px);
margin: 20px auto;
padding: 10px;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
z-index: 151;
}
.image-zoomer {
max-width: 100%;
max-height: 100%;
background-color: rgba(7,30,68,1);
padding: 10px;
border-radius: 10px;
}
/* END ZOOMABLE IMAGE */
Whatever you're doing, you're doing it too early. Use this approach
$(document).ready(function(){
// Paste all of your jquery related code here
})
Updated answer:
$(document).ready(function(){
setTimeout(function(){
// Paste all of your jquery related code here
}, 500)
})
the value 500 is in ms
Probably your <div class="photo"> render after page load
Because of that ,can you try replace
productImageZoom.click(function () {
to
$(document).on("click",'.photo',function() {
I wonder if the productImageZoom length if it does not work
var productImageZoom = $('.photo');
console.log(productImageZoom.length);

Javascript onmouseover background image change

I'm trying to implement this background changer from removed after edits to my personal blog that only resides on my computer (not uploading to the internet), but I don't know what the js for it is? How would I go about adding it to my blog?
I know there's the:
<body style="background-image : url();">
in the html file later followed by the:
<img src="" onmouseover="document.body.style.backgroundImage = 'url()';" width="20" height="20">
Is there anything else besides the js?
Edit: It seems this only works with 12x12 gifs? When I put my own images into the url places, the bg change won't work.
2nd Edit: I found the problem. I had my imgs not named properly.
Here is something that toggles between two images on the background of a div.
let images = ['https://www.gstatic.com/webp/gallery/3.jpg','https://www.gstatic.com/webp/gallery/1.jpg'];
var currentImage = 1;
let myDiv = document.getElementById("myBackground");
myDiv.addEventListener('mouseover', function(event) {
currentImage = currentImage == 0 ? 1 : 0;
event.target.style.backgroundImage = `url('${images[currentImage]}')`;
});
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
<div id="myBackground"></div>
Here is a version using just CSS, but limited to mouse over, resets when you leave the element.
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
#myBackground:hover {
background-image: url('https://www.gstatic.com/webp/gallery/2.jpg');
}
<div id="myBackground"></div>
Here is a version the adds a class to the CSS on mouseover.
let myDiv = document.getElementById("myBackground");
myDiv.addEventListener('mouseover', function(event) {
event.target.classList.add('myOverride');
});
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
#myBackground.myOverride {
background-image: url('https://www.gstatic.com/webp/gallery/2.jpg');
}
<div id="myBackground"></div>
Your code will work just fine. No need of any other js code.

function not working on modal in web browser

i have problem my function not working in mobile browser but when i open in browser desktop work i dont know why... maybe anybody know or have experience like me
i have try this code
$('body').on('click touchstart', '.show_range', function(event) { alert("hello"); })
work in desktop but not in mobile browser
i have try this code when i set id in my link
$(document).on("click", "#show_range", function(event){
alert( "GO" );
});
work in desktop but not in mobile browser
if you are using bootstrap modal then make some change as below,
in bootstrap-responsive.css
.modal {
position: fixed;
top: 3%;
right: 3%;
left: 3%;
width: auto;
margin: 0;
}
.modal-body {
height: 60%;
}
and in bootstrap.css
.modal-body {
max-height: 350px;
padding: 15px;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
OR
try this,
if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
}
You can try the following:
$('#show_range').on("click", function(event){
alert( "GO" );
});
thank for you help guys now my problem solved..
my mistake i set href="javascript:void()" and i change to href="#"

Cannot get div element by id to display gif in internet explorer

I am trying to make a .gif image display in a loading window to alert my user that loading is underway, quite simple. I was doing it using only css and background property like this:
/background: url(ajax-loader.gif) no-repeat center #fff;/
but my .gif was not loading in internet explorer. So I've made a research and found this and, based on J.Davies's solution, I have implemented this instead in my js file:
function ShowProgress() {
if (!spinnerVisible) {
$('div#layer').fadeIn("fast");
$('div#spinner').fadeIn("fast");
spinnerVisible = true;
var pb = $('#spinner');
pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>';
pb.style.display = "";
}
}
My problem is that it works still in chrome, but I get a crash in internet explorer saying that it pb is undefined. Is there a specificity on how to work with jquery and internet explorer? For information, here's my display:
<div id="body">
#RenderSection("featured", false)
<section class="content-wrapper main-content clear-fix">
<section>
#Html.Partial("MessageDisplay")
</section>
<div id="layer"></div>
<div id="spinner">
Loading, please wait...
</div>
#RenderBody()
</section>
</div>
And the css saying that spinner and layer div are hidden:
div#spinner {
display: none;
width: 300px;
height: 300px;
position: fixed;
top: 40%;
left: 45%;
/*background: url(ajax-loader.gif) no-repeat center #fff;*/
text-align: center;
padding: 10px;
font: normal 16px Tahoma, Geneva, sans-serif;
border: 1px solid #666;
margin-left: -50px;
margin-top: -50px;
z-index: 2;
overflow: auto;
}
div#layer {
display: none;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: #a4a3a3;
background-color: rgba(164, 163, 163, 0.5);
z-index: 1;
overflow: auto;
-moz-opacity: 0.5
}
pb is a jQuery object. not a dom reference so there is no innerHTML or style properties in it. You need to use the utility methods provided by jQuery to set those
var pb = $('#spinner');
pb.html('<img src="./ajax-loader.gif" width=200 height=40/>').show();
In your case you can use .html() to set the innerHTML and .show() to make it visible
Change this :
var pb = $('#spinner');
pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>';
pb.style.display = "";
with this :
var pb = $('#spinner');
pb.html('<img src="./ajax-loader.gif" width=200 height=40/>');
pb.css({'display':''});
Plus I must add that something IE8 have issue with fadeIn / fadeOut so I would recommande if you still have a problem to try .show() / hide() instead.
I have accepted Arun's answer because it has helped me get to the solution. Based on his answer and my css, I have finally managed to make this jquery call:
function ShowProgress() {
if (!spinnerVisible) {
$('div#layer').fadeIn("fast");
$('div#spinner').fadeIn("fast");
spinnerVisible = true;
var spinner = $('#spinner');
spinner.append('<img src="../../Content/ajax-loader.gif" width="250" height="250"/>').css('background', '#fff').show();
}
}
This keeps every css element originally present and plays my gif in both internet explorer and all other browsers. Thanks!

How do I get the opposite results?

new to the scene of web developing/design
I've been trying to do this for a week now, but can't seem to figure it out so I was hoping I can get some help, it's basically a light switch
So what I'm trying to do is, when I click the switch the background changes colour, text and image changes as well and vice versa.
Umm here's my attempt, I can get it to change background colour and switch the image, but the text doesn't seem to be changing and I when I re-click it's not changing back to the original state
Here are the images:
http://oi59.tinypic.com/96xhec.jpg
http://oi62.tinypic.com/350ug5l.jpg
html:
<img class="swoff" src="img/switch_off.png">
<span class="msg">Hey, who turn off the lights?</span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>') </script>
<script src="js/main.js"></script>
</body>
CSS:
body {
font-family:'Raleway', sans-serif;
font-size:1em;
text-align:center;
margin-top:31%;
background:#151515;
}
.swoff {
display:block;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width:200px;
height:200px;
}
.msg {
color:#fff;
}
.lighttxt {
color:#3c3c3c;
}
Javascript:
$('.swoff').on('click', function() {
var dark = "Hey, who turn off the lights?";
var light = "It's so bright in here!";
var swon = "img/switch_on.png";
if($('img').attr('src',swon)) {
$('body').css({'background-color':'#FFFFF2'});
$('msg').html(dark);
}
else {
$('img').attr(swon,'src')
$('body').css({'background-color':'#151515'});
$('msg').html(light);
}
I think it's easier to work with CSS classes and use the available jQuery methods (addClass,removeClass, etc).
In jQuery, inside element events, the shortcut $(this) refers to the element itself:
$('element').on('click', function(){ $(this).something(); });
Also, use # to target the ID of elements (#id) and . to target the class (.class), we omit this only for HTML tags (input, img, form, etc).
Runnable snippet:
$('#switch').on('click', function() {
var dark = "Hey, who turn off the lights?";
var light = "It's so bright in here!";
if( $(this).hasClass('swoff') ) {
$(this).removeClass('swoff').addClass('swon');
$('body').css({'background-color':'#FFFFF2'});
$('#msg').html(light).removeClass('darktext').addClass('lighttxt');
}
else {
$(this).removeClass('swon').addClass('swoff');
$('body').css({'background-color':'#151515'});
$('#msg').html(dark).removeClass('lighttxt').addClass('darktext');
}
});
body {
font-family:'Raleway', sans-serif;
font-size:1em;
text-align:center;
background:#151515;
}
#switch {
display:block;
margin: auto;
width:200px;
height:200px;
}
.swoff {
background-image: url('http://i.stack.imgur.com/I7Clv.png');
background-size: 100% 100%;
}
.swon {
background-image: url('http://i.stack.imgur.com/vbKrW.png');
background-size: 100% 100%;
}
.darktxt {
color:#fff;
}
.lighttxt {
color:#3c3c3c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="switch" class="swoff"></div>
<span id="msg" class="darktxt">Hey, who turn off the lights?</span>
I'm not sure what you had in mind with this line:
if($('img').attr('src',swon)) {
If you are trying to say "is the src attribute on the image the same as swon", then you want this:
if($('img').attr('src')==swon) {
Calling attr with one argument (i.e. .attr('src') ) gets the attribute, calling it with two (i.e. .attr('src',swon) ), sets it. So instead of checking if the src is equal to swon, you are instead setting it each time. This is the first reason it wasn't toggling. Your other line $('img').attr(swon,'src') is also whacky (wrong argument sequence).
There's more to fix but hopefully that helps.
NOTE: You're missing "});" at the end of the JS.

Categories