Jump to content

Refactor Javascript to Use jQuery


Recommended Posts

I'm trying to refactor this javascript from this :

var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption

var img = document.getElementsByClassName("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

 

And this is my attempt but i am stuck :

( function( $ ) {

    var modal = $('#myModal');

    var img = $('.myImg');
    var modalImg = $('#img01');
    var captionText = $("#caption");

$("img").click(function(){
  modal.style.display = "block";
  modalImg.src = $this.src;
  captionText.innerHTML = $this.alt;
});

var span = $("close")[0];

$("span").click(function(){
  modal.style.display = "none";
});

} ( jQuery ) );

 

Link to post
Share on other sites

If you assign a jQuery result to a variable, you do not need the $() function to use it.

This should work, though I haven't tested it so there might be a mistake somewhere.

( function( $ ) {

    var modal = $('#myModal');
    var img = $('.myImg');
    var modalImg = $('#img01');
    var captionText = $("#caption");

    img.click(function(){
      modal.show();
      modalImg.attr("src", $(this).attr("src"));
      captionText.html($(this).attr("alt"));
    });

	var span = $(".close").first();
    span.click(function(){
      modal.hide();
    });

} ( jQuery ) );

I do not see any good reason to convert Javascript to jQuery. jQuery is far less efficient and isn't natively built into browsers, requiring a download of an external file before it can run.

  • Like 1
Link to post
Share on other sites
Posted (edited)
31 minutes ago, Ingolme said:

I do not see any good reason to convert Javascript to jQuery.

Excellent. Works great. The reason i wanted to use jQuery is because i couldn't get it to load when using it in a file in WordPress.

Edited by dev4wp
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...