jQuery - Links Stop Working After Page Resize - javascript

I am trying to make my website responsive and have added some jQuery to remove and insert HTML. I am trying to display a popup box when an anchor tag around an image is clicked.
The window appears the first time the page is loaded, but when it has been resized the link no longer works and doesn't display the popup.
// Call hidePopup function upon clicking element with class ".close"
$(function() {
$('.close').click(hidePopup);
});
function hidePopup() {
if (this.id == 'hideP1') {
$('#popup1').addClass('hidePopups');
} else if (this.id == 'hideP2') {
$('#popup2').addClass('hidePopups');
} else if (this.id == 'hideP3') {
$('#popup3').addClass('hidePopups');
}
}
// Call showPopup function upon clicking element with class ".imgClick"
$(function() {
$('.imgClick').click(showPopup);
});
function showPopup() {
if (this.id == 'imgEms') {
$('#popup1').removeClass('hidePopups');
} else if (this.id == 'imgPas') {
$('#popup2').removeClass('hidePopups');
} else if (this.id == 'imgTs') {
$('#popup3').removeClass('hidePopups');
}
}
var LinkedHtml = [
'<img src="assets/img/festival-big.jpg" title="Event Medical Services">',
'<img src="assets/img/ambulance2.png" title="Private Ambulance Services">',
'<img src="assets/img/training_1.jpeg" title="Training Solutions">'
];
var nonLinkedHtml = [
'<img src="assets/img/festival-big.jpg" title="Event Medical Services" id="emsImg">',
'<img src="assets/img/ambulance2.png" title="Private Ambulance Services" id="pasImg">',
'<img src="assets/img/training_1.jpeg" title="Training Solutions" id="tsImg">'
];
$(window).resize(function() {
windowSize = $(window).width();
var anchorIds = ['#imgEms','#imgPas','#imgTs'];
var imageIds = ['#emsImg','#pasImg','#tsImg'];
if (windowSize < 740) {
for (var i = 0; i < imageIds.length; i++) {
$(imageIds[i]).replaceWith(LinkedHtml[i]);
}
} else if (windowSize > 740) {
$(".overlay").addClass("hidePopups");
for (var i = 0; i < anchorIds.length; i++) {
$(anchorIds[i]).replaceWith(nonLinkedHtml[i]);
}
}
});
I do not have much experience with JavaScript nor jQuery and I have been struggling with this issue all day.
Thank you!

What happens if you try to use a delegate instead?
$(function() {
$(document.body).on('click', '.imgClick', showPopup);
});
If this works, then you should try to find a parent element that always exists for the imgClick elements, that is never replaced, and use that as a selector instead of document.body.

Related

content narration in web page, on tab press not going to speak anything if current task(speak anything) not completed

I am using articulate.js(http://www.jqueryscript.net/demo/Lightweight-jQuery-Based-Text-To-Speech-Engine-Articulate-js/) to read content from page and speak it. It is working fine, just not works if it is speaking something and I have press tab then it stops but not reads tab selected content.
some pre-define functions
<script>
function speak(obj) {
$(obj).articulate('speak');
};
function pause() {
$().articulate('pause');
};
function resume() {
$().articulate('resume');
};
function stop() {
$().articulate('stop');
};
</script>
what I have tried
<script>
$(document).ready(function() {
var counter = 0;
setTimeout(function(){
counter +=1;
if (counter == 1){
explode();
}
},1000);
function explode(){
//$('body').articulate('speak'); // Default for play whole content
$('h1').articulate('speak');
}
$('body').keyup(function (e) {
$().articulate('stop');
if (e.which == 9) { // on tab press start speaking selected element
var i=document.activeElement.id;
$('#'+i).articulate('pause').articulate('stop').articulate('speak');
}
else{ // trying to speak what key has been pressed except tab, but not working
var i=document.activeElement.id;
$('#'+i).val().articulate('speak');
}
});
});
</script>
I am also trying to make it audible(to speak keypress) on text box, which is not working
I have make some changes now it is working, but it has certain limitation like it not reads backspace, ctrl, space etc but speak a to z,1 to 0, very well. please improve it
<script>
$(document).ready(function() {
var counter = 0;
setTimeout(function(){
counter +=1;
if (counter == 1){
explode();
}
},1000);
function explode(){
//$('body').articulate('speak'); // Default for play whole content
$('h1').articulate('speak');
}
$('body').keyup(function (e) {
var speaking = $().articulate('isSpeaking');
var paused = $().articulate('isPaused');
// $().articulate('stop');
if (e.which == 9) {
if (speaking) {
$().articulate('pause');
$().articulate('stop');
}
var check =0;
setTimeout(function(){
check +=1;
if (check == 1){
comeback();
}
},1000);
function comeback() {
var i=document.activeElement.id;
$('#'+i).articulate('speak');
}
}
else{
var i=document.activeElement.id;
var m=0;
setTimeout(function () {
m+=1;
if(m==1){
magic();
}
},500);
function magic() {
var tempval=$('#'+i).val();
var lastChar = tempval.substr(tempval.length - 1);
var ht ='<div>'+lastChar+'</div>';
$(ht).articulate('speak');
}
}
});
});
</script>

Handler defined with document.on deleted when object deleted from DOM

I have some severe memory leaks on my SPA. I managed to localize where the leak is, but I can't fix it. I have a code like this :
$(document).on("click.widget", ".glyphicon-collapse-down", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-down")
.addClass("glyphicon-collapse-up");
kendo.fx(contentElement).expand("vertical").stop().play();
});
I can generate widgets over time on my single page, so I need the buttons to have a handler even if they don't exist yet (every widget come with a button group). When I switch from the current page to another, I delete everything from the page and load a new page with an ajax request. And here is appears the memory leak. I suspect that it might lies in the fact that the handlers are not deleted properly.
EDIT : The leak becomes very smaller when I don't include this script in the app :
//expand the widget
$(document).on("click.widget", ".glyphicon-collapse-down", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-down")
.addClass("glyphicon-collapse-up");
kendo.fx(contentElement).expand("vertical").stop().play();
});
//collapse the widget
$(document).on("click.widget", ".glyphicon-collapse-up", function (e) {
var contentElement = $(e.target).closest(".widget").find(".widget-body");
$(e.target)
.removeClass("glyphicon-collapse-up")
.addClass("glyphicon-collapse-down");
kendo.fx(contentElement).expand("vertical").stop().reverse();
});
//remove the widget and updating the layout accordingly
$(document).on("click.widget", ".glyphicon-remove", function (e) {
var contentElement = $(e.target).closest(".widget");
var ancestor = $(contentElement).parent();
var rightColumn = $("#right-column");
var mainColumn = $("#main-column");
kendo.unbind(contentElement);
kendo.destroy(contentElement);
$(contentElement).fadeOut().remove();
// //Widget layout modification on remove
if ((rightColumn.items().length - 1 == 0) && (ancestor.attr("id") == "right-column")) {
if (mainColumn.items().length == 1) {
$("#main-column").removeClass("col-lg-6").hide().addClass("col-lg-12").fadeIn();
}
else if (mainColumn.items().length > 1) {
var firstWidget = mainColumn.items().last();
$(firstWidget).hide().prependTo("#right-column").fadeIn();
}
}
if ((mainColumn.items().length - 1 == 0) && (ancestor.attr("id") == "main-column")) {
if (rightColumn.items().length == 1) {
$("#right-column").removeClass("col-lg-6").hide().addClass("col-lg-12").fadeIn();
}
else if (rightColumn.items().length > 1) {
var firstWidget = rightColumn.items().last();
$(firstWidget).hide().prependTo("#main-column").fadeIn();
}
}
});
//Enable the widget fullscreen
$(document).on("click.widget", ".widget-fullscreen-on", function (e) {
var contentElement = $(e.target).closest(".widget");
contentElement.addClass("fullscreen");
$(e.target)
.removeClass("glyphicon-resize-full")
.removeClass("widget-fullscreen-on")
.addClass("glyphicon-resize-small")
.addClass("widget-fullscreen-off");
});
//Disable the widget fullscreen
$(document).on("click.widget", ".widget-fullscreen-off", function (e) {
var contentElement = $(e.target).closest(".widget");
contentElement.removeClass("fullscreen");
$(e.target)
.removeClass("glyphicon-resize-small")
.removeClass("widget-fullscreen-off")
.addClass("glyphicon-resize-full")
.addClass("widget-fullscreen-on");
});
//Inserts a widget into the page content and modifies the layout accordingly
function insertWidget(jtext) {
jtext.attr("id", "");
if (($('#main-column').items().length == 0) && ($('#right-column').items().length == 0)) {
if ($("#main-column").hasClass("col-lg-12")) {
$(jtext).hide().prependTo('#main-column').fadeIn();
}
else if ($("#right-column").hasClass("col-lg-12")) {
$(jtext).hide().prependTo('#right-column').fadeIn();
}
}
else if ($("#main-column").hasClass("col-lg-12")) {
$("#main-column").removeClass("col-lg-12").addClass("col-lg-6");
$(jtext).hide().prependTo('#right-column').fadeIn();
}
else if ($("#right-column").hasClass("col-lg-12")) {
$("#right-column").removeClass("col-lg-12").addClass("col-lg-6");
$(jtext).hide().prependTo('#main-column').fadeIn();
}
else if ($('#right-column').items().length < $('#main-column').items().length) {
$(jtext).hide().prependTo('#right-column').fadeIn();
}
else {
$(jtext).hide().prependTo('#main-column').fadeIn();
}
}

JavaScript link to another page

I have the next code:
<p>
<img alt="" src="imagini/slide1.png"
style="height: 64px; width: 64px" id="imgClickAndChange"
onclick="changeImage()" />
</p>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "imagini/slide1.png")
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
else
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
}
</script>
That is changing an image (phase 1) after clicking on it into another image(phase 2). I want to link the second image (phase 2) to an index.php page. How do I do that? Is there a way of altering or interfering in the changeImage function.
Use the else block of the if statement you already have to change window.location.
function changeImage() {
if (document.getElementById("imgClickAndChange").src.indexOf("imagini/slide1.png") !== -1) {
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
} else {
window.location = "index.php";
}
}
You could use jQuery to easily attach a click event on the second image only. Or you could have 2 images in the page (one alone and one inside a link) and then hide and show one image or another.
Try something like this:
var myEl = document.getElementById("imgClickAndChange");
var parent = myEl.parentNode();
var link = document.createElement('a');
link.href = 'http://www.google.com';
link.appendChild(myEl);
parent.removeChild(myEl);
myEl.src = "imagini/platform.png";
parent.appendChild(link);
try this
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "imagini/slide1.png")
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
else
{
document.location.href="index.php";
}
}

Run JS when screen width is this

I have this js that I want to only run when the screen size is 800 or below, as it enables swiping. Please help I cant figure out away.
var snapper = new Snap({
element: document.getElementById('content')
});
and the Snap is linked by
Thanks for any help.
EDIT:
<script>
$(function() {
var SmartMenu = $('#SmartMenu');
MainMenu = $('.MainMenu');
PortfolioMenu = $('#Portfolio');
PortfolioSubMenu = $('.subMenu');
SmartMenuOpen = $('#SmartMenuOpen');
wrapperHeader = $('.wrapperHeader-Top');
if(window.innerWidth <= 800) {
var snapper = new Snap({
element: document.getElementById('W')
});
}
$(SmartMenu).on('click', function(a) {
if( snapper.state().state=="left" ){
snapper.close();
} else {
snapper.open('left');
}
});
</script>
if(window.innerWidth <= 800) {
// Your code here
}
That should do the trick the first time.
EDIT 1:
If you want it to change whenever the browser is resized
window.onresize = function(event) {
if(window.innerWidth <= 800) {
// Your code here
}
}
But do make sure that the code you include will work correctly if called multiple times when the browser is resized.
EDIT 2 With access to jQuery: #2 to support Snap API and to support init
var snapper;
function initSnapper() {
if($(window).innerWidth() <= 800) {
if(snapper === undefined) {
snapper = new Snap({
element: document.getElementById('W')
});
}
else {
snapper.enable();
}
}
else if(snapper !== undefined) {
snapper.disable();
}
}
$(window).resize(initSnapper);
initSnapper();
This will initialize snapper when the page loads and will call initSnapper when the page is resized.
And you will want to check if snapper exists before checking the state like
if( snapper && snapper.state().state=="left" ){
// snapper code
}

Is there a way to convert this jquery code to javascript?

I'm trying to create a tab menu. And I need this coded in regular javascript, not jquery.
$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content
//On Click Event
$("ul.general_info_tabs li").click(function() {
$("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".general_info_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
The core of what you want to do is below - I'm sure there are a thousand different ways to do each task:
Remove a CSS class from an element:
var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
if(classes[i] == removeClass)
classes[i] = "";
document.getElementById([id]).className = classes.join(" ");
Add a CSS class to an element:
document.getElementById([i]).className += " " + addClassName;
Hide an element:
document.getElementById([i]).style.display = "none";
Fade an element:
// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
if (opacity < 100) {
el.style.opacity = opacity / 100;
el.style.filter = "alpha(opacity=" + opacity + ")";
opacity += 5;
setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
}
}
To find all elements by CSS and tag name:
var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
if(all[i].className.replace(searchClassName, "") != all[i].className) {
matches.push(all[i].className);
}
}
// do something with (i.e., return or process) matches
And for the record, I find it encouraging, not unreasonable, that a person using the jQuery library wants to know how to do get things done with native JS/DOM.
More functions to complement Brian's post. Good luck.
EDIT: As I mentioned I would change the class=general_info_content to id=general_info_content1.
function attach(el, event, fnc) {
//attach event to the element
if (el.addEventListener) {
el.addEventListener(event, fnc, false);
}
else if (document.attachEvent) {
el["on" + event] = fnc; // Don not use attachEvent as it breaks 'this'
}
}
function ready() {
// put all your code within $(function(){}); here.
}
function init() {
attach(document, "readystatechange", function () {
if (document.readyState == "complete") {
ready();
}
});
}

Categories

Resources